johnno1962 / injectionforxcode

Runtime Code Injection for Objective-C & Swift
MIT License
6.55k stars 565 forks source link

Could not cast in func prepare for segue #210

Open bonyadmitr opened 7 years ago

bonyadmitr commented 7 years ago

Steps to reproduce

  1. start project
  2. make injection with saving file
  3. make any push VC with implemented func prepare(for segue: , sender: ) and force cast in it. (see code and screenshots)
  4. error

Code:

import UIKit

class QController: UIViewController {

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "QQQ" {
            let vc = segue.destination as! ViewController
            vc.view.backgroundColor = UIColor.black
        }
    }

}

class ViewController: UITableViewController {

    @IBOutlet weak var someView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
//        someView.backgroundColor = UIColor.green
//        someView.layer.cornerRadius = 30
//        someView.layer.borderWidth = 10
//        someView.layer.borderColor = UIColor.red.cgColor
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 50
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = "Row \(indexPath.row + 1)"
//        cell.textLabel?.font = UIFont.systemFont(ofSize: 30)
//        cell.layer.borderWidth = 3
//        cell.layer.borderColor = UIColor.magenta.cgColor
        return cell
    }
}

Error:

Could not cast value of type 'InjectionTest.ViewController' (0xb0de8) to 'InjectionTest.ViewController' (0xdb07314).

Screenshots:

screen shot 2017-04-12 at 15 06 49 screen shot 2017-04-12 at 15 07 07

johnno1962 commented 7 years ago

This is a known problem I’m afraid with casting a class that has been injected.

bonyadmitr commented 7 years ago

Do you have any plans to fix it? I think it is very important.

sosoyososo commented 6 years ago

Run into this situation too. Steps to reproduce:

  1. start xcode
  2. modify swift code of a view controller create from storyboard
  3. inject source file
  4. Recreate this controller from storyboard and force cast to its type.
johnno1962 commented 6 years ago

You have to keep the definition of classes you are instantiating separate from classes you are injecting.