我有一个与成员类具有一对多关系的托管对象。当我为成员添加观察者时,它起作用了。当一个新成员添加到关系中时,将使用新对象调用 observeValueForKeyPath 并且更改字典包含新成员对象。但是,observeValueForKeyPath 将在所有值为零的情况下第二次触发并更改字典 new="NULL"。第二个触发器是什么?我设置了一个断点,但不确定是谁触发的。
@interface FooObject : NSManagedObject {}
@property (nonatomic, strong) NSString *fooId;
@property (nonatomic, strong) NSSet* members;
@end
@implementation FooObject
@dynamic fooId;
@dynamic members;
- (NSMutableSet*)membersSet {
[self willAccessValueForKey:@"members"];
NSMutableSet *result = (NSMutableSet*)[self mutableSetValueForKey:@"members"];
[self didAccessValueForKey:@"members"];
return result;
}
- (void)registerObservers {
[self addObserver:self
forKeyPath:@"members"
options:NSKeyValueObservingOptionNew
context:nil];
}
- (void)unregisterObservers {
@try{
[self removeObserver:self forKeyPath:@"members"];
}@catch(id anException){
//do nothing, obviously it wasn't attached because an exception was thrown
}
}
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
id valueNewSet = [change objectForKey:NSKeyValueChangeNewKey];
if (![valueNewSet isKindOfClass:[NSSet class]]) {
// not a NSSet, it contains <null> value
NSLog(@"%@", change);
NSLog(@"%@", object);
}
if ([[change objectForKey:NSKeyValueChangeKindKey] intValue] == NSKeyValueChangeInsertion) {
// insert change is valid, process the changes
}
}
@end
日志输出:
{
kind = 1;
new = "<null>";
}
<FooObject: 0xfa9cc60> (entity: FooObject; id: 0xfa9be00 <x-coredata://39DB31FD-6795-4FDE-B700-819AB22E5170/SHInterest/p6> ; data: {
fooId = nil;
members = nil;
})
编辑 1 我在 NSLog(@"%@", change); 这是堆栈跟踪,但对于确定谁进行此调用并没有真正的帮助。
主 -> UIApplicationMain -> NSKeyValueNotifyObserver -> observeValueForKeyPath:ofObject:change:context
编辑 2 也许这仍然是一个错误? http://www.cocoabuilder.com/archive/cocoa/182567-kvo-observevalueforkeypath-not-reflecting-changes.html