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

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

问题描述

我有一个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.

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

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