这是一个迟到的答案,但我认为这是一种常见的情况,而且答案肯定不是显而易见的。
我通常会观察 managedObjectContext 的变化,然后检查是否有任何已更改的对象是我想要注意的对象。所以,在你的NSManagedObject
子类中:
// We need to register for the notification in both awakeFromFetch
// AND awakeFromInsert, since either one could be called, depending on
// if the object was previously-created or not
- (void)awakeFromFetch {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(managedObjectContextDidChange:) name: NSManagedObjectContextObjectsDidChangeNotification object:[self managedObjectContext]];
}
- (void)awakeFromInsert {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(managedObjectContextDidChange:) name: NSManagedObjectContextObjectsDidChangeNotification object:[self managedObjectContext]];
}
- (void)managedObjectContextDidChange:(NSNotification *)notification {
// Get a set containing ALL objects which have been changed
NSSet *insertedObjects = [[notification userInfo] objectForKey:NSInsertedObjectsKey];
NSSet *updatedObjects = [[notification userInfo] objectForKey:NSUpdatedObjectsKey];
NSSet *deletedObjects = [[notification userInfo] objectForKey:NSDeletedObjectsKey];
NSSet *changedObjects = [insertedObjects setByAddingObjectsFromSet:updatedObjects];
changedObjects = [changedObjects setByAddingObjectsFromSet:deletedObjects];
if ([changedObjects intersectsSet:[self versions]]) {
[self willChangeValueForKey:@"appCast"];
[self didChangeValueForKey:@"appCast"];
}
}
从性能的角度来看,这当然不是理想的,因为每次对象图中的任何内容发生更改时都会触发此通知,但我发现它是实现此目的最直接的方法。