0

我将以下方法设置为 anNSComboBox和两个NSTextFields 的操作:

- (IBAction)valueChanged:(id)sender
{
    if (sender == comboBox) {
        [myModel setFoo1:[comboBox intValue]];
    } else if (sender == intTextField) {
        [myModel setFoo2:[intTextField intValue]];
    } else if (sender == floatTextField) {
        [myModel setFoo3:[floatTextField floatValue]];
    }
}

我想知道是否可以将该方法变成这样,以提高可维护性:

- (IBAction)valueChanged:(id)sender
{
    [myModel setValue:[sender value] forKey:[sender identifier]];
}

不幸的是,它不是那样工作的。我收到以下错误:

[NSComboBox value]: unrecognized selector sent to instance 0x7fed42029430

我如何以统一的方式(即作为对象)从控件中获取值,无论是否intfloat?我在模型上使用的 KVCsetValue:forKey:方法应该能够推断出值对象的实际类型(即NSNumber本例中的类型),对吧?

或者这根本不可能?(我知道我可以使用绑定将 UI 控件绑定到模型的值字段,但这不是我想要做的。)

4

1 回答 1

1

由于NSTextFieldNSComboBox都是 的子类NSControl,因此您应该能够以-(id)objectValue统一的方式使用来获取控件的值(或选定的值)。

于 2012-06-10T02:35:53.153 回答