问题描述:

I'm trying to solve problem which appears during this case:

  1. User can initiate data loading from external source, when data is loaded, it is saved via CoreData. Then it is displayed in some views and some other classes got references to NSManagedObjects.
  2. Data loading can be initiated by other condition (for example, when application resumes from background). New external data is received, dataController deletes previous and creates new data. And here is the problem.

    I want to notify all data consumers-classes that they should load new instances (send them references to deleted objects, so they can compare references with ones they own and determine should they ask for new data version or not). But after deletion consumer-class has reference to fault without properties, its ObjectID is useless (because new instance was saved) and I don't know how load its new version.

I can implement some NSManagedObject wrapper:

@interface Model : NSObject

- (id)initWithUniqueId:(id)uniqueId dataObject:(NSManagedObject *)dataObject;

@property (nonatomic, strong, readonly) id uniqueId;

@property (nonatomic, strong, readonly) NSManagedObject *dataObject;

@end

This object can reload itself after dataObject becomes fault. But maybe this approach is wrong and this overhead is not needed? And NSManagedObject should be deleted only if it is really deleted, not updated? And then if object is updated, we can use KVO to handle properties changes, and if object is deleted, we can observe NSManagedObjectContext notifications for changes and look for deleted objects.

I just want to know which way would you prefer and why (maybe you like some other approach)? Thanks in advance.

网友答案:

If you are using an external data source, your own version of some kind of unique ID makes sense.

Then everything becomes simple. You load the data, update the persistent store when you save the context, and send of a notification via the NSNotificationCenter. All listeners can now simply update their data by re-fetching.

(Fetched results controllers that implement the delegate methods do not even have to be notified via the notification center.)

相关阅读:
Top