Search code examples
ioscore-dataswiftnsmanagedobject

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

Solution

  • 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
    }