简体   繁体   中英

Pass NSManagedObject from one view controller to another

I'm developing a table view based app using CoreData with Swift. I'm trying to pas an NSManagedObject from one view controller to another. Below is my code and error that I get.

In ViewController1.swift I have the following code:

override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {

    if segue.identifier == "Edit" {
        var selectedItem: NSManagedObject = myData[self.tableView.indexPathForSelectedRow().row] as NSManagedObject
        let vc2: ViewController2 = segue.destinationViewController as ViewController2

        vc2.item = selectedItem

    }
}

In ViewController2.swift :

class ViewController2: UIViewController {

    @NSManaged var item : NSManagedObject

    override func viewDidLoad() {
        super.viewDidLoad()
    }
    // Other default func
}

Error when I segue to ViewController2 :

[_TtC6myData18ViewController2 setItem:]: unrecognized selector sent to instance 0x111530000

The @NSManaged qualifier is only supposed to be used for properties in an NSManagedObject subclass, so it shouldn't be used in your situation. This should work,

class ViewController2: UIViewController {

    var item : NSManagedObject! 

    override func viewDidLoad() {
        super.viewDidLoad()
    }
    // Other default func
}

Set a breakpoint on exceptions so that you can see what the actual error/message in the NSException is. You will also be able to see where it is thrown.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM