OSX Cocoa - 如何测试多个NSTextField中的更改

时间:2013-06-02 10:09:35

标签: objective-c cocoa osx-mountain-lion nstextfield

我正在尝试测试某些NSTextFields的更改。

我正在使用:

- (void)controlTextDidEndEditing:(NSNotification *)notification {

    if ([notification object] == field1) 
        NSLog(@"field1: stringValue == %@", [field1 stringValue]);

    if ([notification object] == field2) 
        NSLog(@"field2: stringValue == %@", [field2 stringValue]);

    if ([notification object] == field3)
        NSLog(@"field3: stringValue == %@", [field3 stringValue]);

}

这有效,但我想知道是否有更好的方法。感谢

2 个答案:

答案 0 :(得分:1)

这很好。

field1等我期待成为出路。

你可以做得更好一点:

- (void)controlTextDidEndEditing:(NSNotification *)notification {

    if ([notification object] == field1) 
        NSLog(@"field1: stringValue == %@", [field1 stringValue]);

    else if ([notification object] == field2) 
        NSLog(@"field2: stringValue == %@", [field2 stringValue]);

    else if ([notification object] == field3)
        NSLog(@"field3: stringValue == %@", [field3 stringValue]);

}

答案 1 :(得分:1)

您可以使用Key-Value-Observing(KVO)来捕获任何值更改。

[field1 addObserver:self
         forKeyPath:@"text"
             options:(NSKeyValueObservingOptionNew |
                        NSKeyValueObservingOptionOld)
                context:NULL];

你必须在观察者中实现方法:

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

if ([keyPath isEqual:@"text"]) {
      if ( [object isMemberOfClass: [//class of object you have passed //]]){
         //project class you are processing and then use  a log
         NSLog(@"object: stringValue == %@", [field2 stringValue]);
      }

}
/*
 Be sure to call the superclass's implementation *if it implements it*.
 NSObject does not implement the method.
 */
[super observeValueForKeyPath:keyPath
                     ofObject:object
                       change:change
                       context:context];

}