1

我正在尝试测试一些 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]);

}

这行得通,但我想知道是否有更好的方法。谢谢

4

2 回答 2

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];

}

于 2013-06-02T11:23:24.083 回答
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]);

}
于 2013-06-02T10:25:55.180 回答