简体   繁体   中英

Are core data changes reflected in local NSManagedObject subclass vars?

I'm using NSFetchResultsController to populate a UITableView. The table view is populated with my "Contact" NSManagedObject subclass. When one of the table cells is selected, I'm passing the selected Contact to the destination view controller:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == kChatSegue {
        if let controller = segue.destinationViewController as? ChatViewController {
            if let theSelectedContact = self.selectedContact {
                controller.contact = theSelectedContact
            }
        }
    }
}

As you can see from the above code, ChatViewController has a local var which holds the selected contact.

Now for the problem. When changes are made to that particular Contact object elsewhere in the app and saved to the managed object context, the changes are not accurately reflected for ChatViewController's local contact var. Will changes to a NSManagedObject be reflected in local vars for that object? If not, how can I force the var to update so that it reflects the current saved values?

Managed objects do not automatically reflect changes made to the underlying persistent store. Once fetched, they keep their state until you change it. This is generally a good thing-- you wouldn't want unsaved changes to be unexpectedly wiped out, for example.

If you want to force one copy to load changes made elsewhere, use refreshObject(:,mergeChanges:) on your NSManagedObjectContext with the second argument set to true . That will tell the context to reload the object's data to reflect the current saved state. You can observe NSManagedObjectContextDidSaveNotification to find out when there might be changes that need to be loaded.

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