布尔属性上的KVO,而不是调用observeValueForKeyPath



我有一个appDelegate,它的属性myWindow为MyWindowClass。我需要从myWindow观察布尔属性。我有一个CustomViewController,它需要观察布尔值的变化。如果我想添加Observer,我会在ViewController中执行以下操作:

LayerWindow *w = ((AppDelegate*)[UIApplication sharedApplication].delegate).window;
    [w addObserver:self forKeyPath:@"touchInsideLayerWindow" options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) context:nil];

在ViewController中,我有

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context 

方法定义,也在头文件中。

在WindowClass中,我有以下代码:

[self setValue:[NSNumber numberWithBool: YES]forKey:@"touchInsideLayerWindow"];
 NSLog(@"isTouchInside %@", self.touchInsideLayerWindow ? @"YES" : @"NO");

从未调用ViewController中的方法observeValueForKeyPath。有人知道怎么了吗?感谢

看起来有一个问题是,您说属性是BOOL,但您试图在setValue调用中将其设置为NSNumber

第二:如果您使用@synthesize制作setter,那么只要您使用点语法,KVO就会自动得到支持。

   self.touchInsideLayerWindow = YES;

用替换此行[self setValue:[NSNumber numberWithBool: YES]forKey:@"touchInsideLayerWindow"];

[self willChangeValueForKey:@"touchInsideLayerWindow"];
[self setValue:[NSNumber numberWithBool: YES]forKey:@"touchInsideLayerWindow"];
[self didChangeValueForKey:@"touchInsideLayerWindow"];

我已经解决了这个问题,KVO的代码是正确的,错误在其他地方。我在对象上调用addObserver,那个并没有正确初始化。

最新更新