2011-06-29 28 views
2

值,但下面的代碼不起作用,因爲「observeValueForKeyPath」功能不會被調用,雖然我不斷變化的的NSTextField文:如何觀察這個看起來簡單的的NSTextField

- (void)awakeFromNib 
{ 
    [myNSTextField addObserver:self forKeyPath:@"value" options:NSKeyValueObservingOptionOld context:nil]; 
} 

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context 
{ 
    NSLog(@"observeValueForKeyPath"); 
} 

從不打印日誌消息@「observeValueForKeyPath」。我試着觀察鑰匙@「stringValue」,但這並不起作用...

我錯過了什麼?

回答

-1
[[NSNotificationCenter defaultCenter] addObserverForName:NSTextViewDidChangeSelectionNotification 
      object:self.textView 
      queue:[NSOperationQueue mainQueue] 
      usingBlock:^(NSNotification *note){ 
       NSLog(@"Text: %@", self.textView.textStorage.string); 
      }]; 
+0

該代碼是用於'NSTextView',而不是一個'NSTextField'。 [This answer](http://stackoverflow.com/a/11488611/39974)建議設置一個實現'NSTextFieldDelegate'協議並實現'controlTextDidChange:'委託方法的委託。 –

0
[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(textFieldDIdChange:) 
              name:NSControlTextDidChangeNotification 
              object:self.textField]; 
相關問題