KVO对象属性在多对多关系中

时间:2011-12-01 05:34:38

标签: objective-c ios cocoa-touch core-data key-value-observing

我有一个核心数据对多关系,包括父< --->>儿童。我想设置一个键值观察机制,这样当任何一个Child对象的属性(例如firstName,lastName)发生变化时,它会触发一个通知。使用标准KVO语法时:

[self.parentObject addObserver:self forKeyPath:@"children" options:NSKeyValueObservingOptionNew context:NULL]

这仅在关系本身被修改时通知(即,从关系中添加或删除Child对象),而不是在其中一个Child对象的属性发生更改时。显然这就是设计操作的方式,因此发生这种情况没有任何问题,但我怎样才能使用KVO来达到我想要的要求呢?

提前致谢!

2 个答案:

答案 0 :(得分:4)

AFAIK没有内置的方法来通过一行代码观察集合对象属性。相反,当您从集合中插入/删除对象时,您必须添加/删除观察者。

可在此处找到解释和示例项目:https://web.archive.org/web/20120319115245/http://homepage.mac.com/mmalc/CocoaExamples/controllers.html (参见“观察集合与观察集合中对象的属性不同”)

<强>更新
链接破了 - 我把它改成了archive.org快照。

答案 1 :(得分:3)

有点迟到的答案,但也许这对谷歌搜索的人有用。

您可以使用谓词NSFetchedResultsController为实体子设置@"parent == %@", child,然后将您的控制器添加为该fetchedResultController的委托。当子项的任何属性发生更改以及添加时,将调用该委托。 下面是一个示例代码。我还添加了一个排序描述符,用于将子项按名称排序到

...
NSFetchRequest* fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Child"];
fetchRequest.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]];

NSPredicate* predicate = [NSPredicate predicateWithFormat:@"parent = %@", parent];
self.fetchResultsController.fetchRequest.predicate = predicate;

self.fetchResultsController = [[NSFetchedResultsController alloc] 
     initWithFetchRequest:fetchRequest managedObjectContext:context 
     sectionNameKeyPath:nil cacheName:nil];

self.fetchResultsController.delegate = self;
...

然后实现委托方法

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
   atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
  newIndexPath:(NSIndexPath *)newIndexPath {

您实现所需的任何其他委托方法(该文档有一个非常好的代码片段

相关问题