简体   繁体   中英

Passing Core Data object from tableViewController to TabBarController

I'm trying to pass Core Data object from the list in the tableViewController to TabBarController to parse it in the childViews, I perform segue to subclassed TabBarController

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if let objs = controller.fetchedObjects , objs.count > 0 {
        let casE = objs[indexPath.row]
        performSegue(withIdentifier: "showDetail", sender: casE)
    }
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showDetail" {
        if let destination = segue.destination as? CaseDetail {
            if let casE = sender as? Case {
                destination.casE = casE
            }
        }
    }
}

So pass it to tabBarController

class CaseDetail: UITabBarController {

    var casE: Case?
}

And trying to get it in the child views viewDidLoad

override func viewDidLoad() {
    super.viewDidLoad()

    let tbvc = self.tabBarController as! CaseDetail
    casE = tbvc.casE
    print(casE as Any)
}

But still I got nil, does anyone know other methods of passing data?

Thank you for any advice and help!

Alright, after reading Apple Documentation, I've found a nice note

Whenever you are passing NSManagedObject references in your application, it is beneficial to declare them as weak references. This helps to protect your view controller in the event of the NSManagedObject being deleted and leaving a dangling reference to a non-existent object. When the property is declared as weak it is automatically set to nil when the object is deleted.

So that made a point, and I changed TabBarController subclass:

class CaseDetail: UITabBarController {

      weak var casE: Case? 
}

And now it works perfect!

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