简体   繁体   中英

Core Data NSManagedObject Changes

I am using a simple Master Detail scenario where the master uses a fetched results controller to populate its tableview. When a row is selected, the respective NSManagedObject is passed to the detail view controller where it is used to populate a few UILabels. I added an EditorViewController to allow some of the fields to be updated by the user. On save, I dismiss the EditorViewController and go back to the Detail view controller. The save uses the context assigned to the NSManagedObject.

What is the best way to know that the object in question changed so I can update the UI in the Detail VC? Currently, if I try to update the UILabels in the Detail VC, I don't see any of the new values for the object's properties. I know a delegate/protocol scenario would likely work but I am curious if there something already in place that I can use – a notification I can look for to update the object or if I should have a fetched results controller on the details screen? Not sure the proper path to take here.

NSFetchedResultsController is a most common solution to this problem. It listens for changes in the context and updates the table view's content accordingly. Your question is rather general, so I'll leave a link to a very good article showing how to use it properly .

You can use NSFetchedResultsController and register fetch request for that object (I think it is good solution). Alternatively you can listen for notifications like NSManagedObjectContextDidSaveNotification , but I would not recommend it. Or you can pass an object to your EditorViewController and update properties there directly.

It's hard to say without seeing any code what you are going for, but the other common pattern for working with CoreData makes use of the Model-View-Controller(MVC) paradigm to stage info from your data store in a class variable, then your interface consumes from that class variable. You worry about saving, updating and refreshing the data between CoreData and your class variable separately from your interface consuming that data.

A typical workflow would then be:

//User does something that creates new info
//Store that info permanently in CoreData
//Refresh the class Variable by loading from CoreData (you can also skip this by updating the class variable simultaneously while saving to CoreData, but this is really sloppy and problematic. Better to save then re-fetch)
//Update your interface from the class Variable

Alternately, you could try Key Value Observing? but I'm not sure it's right for your situation.

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