我有一个用一个一对多的关系,成员类管理对象。 当我添加了观察员的成员,它的工作。 当一个新成员添加到所述关系,所述observeValueForKeyPath将与新的对象被调用,并且变化词典包含新成员对象。 然而,observeValueForKeyPath将触发第二次的所有值为零,并更改词典新=“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;
})
EDIT 1 I在NSLog的设置断点(@ “%@”,变更); 这是堆栈跟踪,但没有真正有助于弄清楚谁使这一呼吁。
主 - > UIApplicationMain - > NSKeyValueNotifyObserver - > observeValueForKeyPath:ofObject变化:上下文
编辑2也许这仍然是一个错误? http://www.cocoabuilder.com/archive/cocoa/182567-kvo-observevalueforkeypath-not-reflecting-changes.html