2013-02-14 16 views
2

我有一個appDelegate,它有一個myWindow屬性MyWindowClass。我需要從myWindow觀察bool屬性。比我有一個CustomViewController,需要觀察布爾值的變化。 如果我想的addObserver我不繼的ViewController:關於bool屬性的KVO,不能調用observeValueForKeyPath

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

在視圖控制器我已經定義

- (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"); 

方法observeValueForKeyPath永遠不會被調用。有誰知道,什麼是錯的? 感謝

回答

0

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

嗯,這並沒有什麼變化,因爲基本上和我的代碼基本相同,一般來講都是這樣。 – 2013-02-14 11:14:34

+0

是的,它基本上是一樣的,沒有hCrenge'和'didChange'調用:)。嘗試添加這兩個 – croyneaus4u 2013-02-14 11:19:33

3

看起來像一個問題是,你說的屬性是BOOL替換此行[self setValue:[NSNumber numberWithBool: YES]forKey:@"touchInsideLayerWindow"];,但你試圖將它設置爲NSNumbersetValue通話。第二:如果您使用@synthesize製作引用程序,那麼只要您使用點語法,就會自動支持KVO。

self.touchInsideLayerWindow = YES; 
+0

以及Iam意識到這一點,但我沒有找到任何其他方式,如何設置布爾值,因爲它不是對象... – 2013-02-14 11:15:42

+0

甚至在我有解決方案之前,我已經使用了點語法目前,但也沒有效果。 :( – 2013-02-14 11:16:25

+0

如@sellers所示,使用'@ synthesize'提供的KVO自動支持 – croyneaus4u 2013-02-14 11:23:14

0

我已經解決了這個問題,KVO的代碼是正確的,錯誤在別處。我在對象上調用addObserver,但沒有正確初始化。