How can I track/observe all changes within a subgraph?

柔情痞子 提交于 2019-11-28 13:41:41

问题


I have a NSManagedObjectContext in which I have a number of subclasses of NSManagedObjects such that some are containers for others. What I'd like to do is watch a top-level object to be notified of any changes to any of its properties, associations, or the properties/associations of any of the objects it contains.

Using the context's 'hasChanges' doesn't give me enough granularity. The objects 'isUpdated' method only applies to the given object (and not anything in its associations). Is there a convenient (perhaps, KVO-based) was I can observe changes in a context that are limited to a subgraph?


回答1:


You will want to listen for the NSManagedObjectContextObjectsDidChangeNotification to pick up all changes to your data model. This can be done using code like the following:

[[NSNotificationCenter defaultCenter] 
      addObserver:self 
         selector:@selector(handleDataModelChange:) 
             name:NSManagedObjectContextObjectsDidChangeNotification 
           object:myManagedObjectContext];

which will trigger -handleDataModelChange: on any changes to the myManagedObjectContext context.

Your -handleModelDataChange: method would look something like this:

- (void)handleDataModelChange:(NSNotification *)note
{
    NSSet *updatedObjects = [[note userInfo] objectForKey:NSUpdatedObjectsKey];
    NSSet *deletedObjects = [[note userInfo] objectForKey:NSDeletedObjectsKey];
    NSSet *insertedObjects = [[note userInfo] objectForKey:NSInsertedObjectsKey];

    // Do something in response to this
}

As you can see, the notification contains information on which managed objects were updated, deleted, and inserted. From that information, you should be able to act in response to your data model changes.




回答2:


here's a simple example in Swift:

    NotificationCenter.default.addObserver(forName: .NSManagedObjectContextObjectsDidChange, object: nil, queue: nil) { note in
        if let updated = note.userInfo?[NSUpdatedObjectsKey] as? Set<NSManagedObject>, updated.count > 0 {
            print("updated: \(updated)")
        }

        if let deleted = note.userInfo?[NSDeletedObjectsKey] as? Set<NSManagedObject>, deleted.count > 0 {
            print("deleted: \(deleted)")
        }

        if let inserted = note.userInfo?[NSInsertedObjectsKey] as? Set<NSManagedObject>, inserted.count > 0 {
            print("inserted: \(inserted)")
        }
    }



回答3:


for me it's just lost following two func, maybe this save hours for someone

func controllerWillChangeContent(controller: NSFetchedResultsController) {
    tableView.beginUpdates()
}

func controllerDidChangeContent(controller: NSFetchedResultsController) {
    tableView.endUpdates()
}


来源:https://stackoverflow.com/questions/2463950/how-can-i-track-observe-all-changes-within-a-subgraph

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!