如何跟踪/观察子图中的所有更改? [英] How can I track/observe all changes within a subgraph?

查看:130
本文介绍了如何跟踪/观察子图中的所有更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个NSManagedObjectContext,其中我有许多NSManagedObjects的子类,有些是其他人的容器。我想做的是观察一个顶级对象,通知它对任何属性,关联或它包含的任何对象的属性/关联的任何更改。

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.

使用上下文的'hasChanges'并没有给我足够的粒度。对象'isUpdated'方法仅适用于给定对象(而不是其关联中的任何对象)。是否有一个方便的(也许是基于KVO的)我可以观察上下文中仅限于子图的变化?

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?

推荐答案

您将需要侦听 NSManagedObjectContextObjectsDidChangeNotification 以获取对数据模型的所有更改。这可以使用以下代码完成:

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];

会触发 -handleDataModelChange:更改 myManagedObjectContext 上下文。

您的 -handleModelDataChange :方法看起来像这样:

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.

这篇关于如何跟踪/观察子图中的所有更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆