【问题标题】:OSX Cocoa - How to test for changes in multiple NSTextFieldsOSX Cocoa - 如何测试多个 NSTextFields 的变化
【发布时间】:2013-06-02 10:09:34
【问题描述】:

我正在尝试测试一些 NSTextField 的变化。

我正在使用:

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

}

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

【问题讨论】:

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


    【解决方案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]);
    
    }
    

    【讨论】:

    • @DavidDelMonte:一个建议“永远不要在 24 小时内接受答案,除非你得到了多个答案,并且一个答案有很大的支持率。
    【解决方案2】:

    您可以使用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];
    

    }

    【讨论】:

    • 也谢谢你。无论哪种方式都存在任何性能问题吗? (我有大约 10 个字段)
    • KVO 是 Cocoa 框架的一部分——猜想这对于大多数解决方案来说应该足够快了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-07
    • 1970-01-01
    • 1970-01-01
    • 2015-03-27
    相关资源
    最近更新 更多