2014-10-27 126 views
0

我在h文件中聲明瞭@property (strong, nonatomic) NSString *data;,並將另一個類的NSString傳遞給「data」。我想檢測「數據」是否更新,所以我嘗試了下面的代碼,但它不起作用。如何使方法檢測變量是否發生了變化?

-(void)didChangeValueForKey:(NSString *)key { 

    [super didChangeValueForKey:key]; 
    if ([key isEqualToString:@"data"]) { 
     // do something  
    } 
} 

任何人都知道如何解決這個問題?

謝謝你,對不起我的英文。

+0

http://google.com/search?q=cocoa+key+value+observation+guide – 2014-10-27 08:27:58

+2

如果您想要在聲明屬性的類內檢測到更改,那麼您可以創建自定義設置器 – Paulw11 2014-10-27 08:36:17

回答

3

要做到這一點的方法是使用鍵值觀察

假設你有一個對象myObject與屬性data那麼你可以做這樣的事情...

[self.myObject addObserver:self forKeyPath:@"data" options:NSKeyValueObservingOptionNew context:nil]; 

然後你的方法...

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context 
{ 
    // if you observer multiple properties then they will all fire this method 
    // so you need to determine that the right property is being observed 

    if (object == self.myObject 
     && [keyPath isEqualToString:@"data"]) { 
     // if you are here then you know the object that changed is myObject 
     // and the property is the data property. 

     id theNewData = change[NSKeyValueChangeNewKey]; 
     // this is the new state of the data 
     // you can also get the old state by using different options when adding the observer. 
    } 
} 

你可以閱讀更多關於它in the Apple documentation about KVO

0

使用鍵值編碼 - 這在用戶界面更新中使用很多ref使用這個link

相關問題