1つのアプローチは、KVOを使用することです。特に、インスタンスを'sのButtonText
オブザーバーとして追加します。buttonField
stringValue
より詳細には、ファイルButtonText
で、@property IBOutlet buttonField
が設定されたら(つまり、ButtonText
がNSWindowController
サブクラスの場合、で-windowDidLoad
、の場合ButtonText
がのNSViewController
サブクラスである場合-loadView
)、を呼び出します。
[self.buttonField addObserver:self
forKeyPath:@"stringValue"
options:0
context:&ButtonTextKVOContext];
ButtonTextKVOContext
以前にファイルで次のように定義します。
static int ButtonTextKVOContext = 0;
次に、次のようにオーバーライドobserveValueForKeyPath:ofObject:change:context:
します。
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if (context != &ButtonTextKVOContext) {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
return;
}
if (object == self.buttonField) {
if ([keyPath isEqualToString:@"stringValue"]) {
NSLog(@"controlTextDidChange: %@", _buttonField.stringValue);
}
}
}
編集
ButtonText
はまたはのサブクラスではないNSWindowController
ため、NSViewController
少し異なるアプローチを使用します。以前と同じように、「設定されたら」の観察を開始したいと思います@property IBOutlet buttonField
。これを行うには、プロパティbuttonField
を合成してメンバー変数mButtonField
を書き込みます
@synthesize buttonField = mButtonField;
buttonField
次のようにのセッターをオーバーライドします。
- (void)setButtonField:(NSTextField *)buttonField
{
[self stopObservingButtonField];
mButtonField = buttonField;
[self startObservingButtonField];
}
ボタンフィールドの割り当てが解除されたときにもボタンフィールドの監視が停止することを確認する必要があるため、次ButtonText
のようにオーバーライド-dealloc
します。
- (void)dealloc
{
[self stopObservingButtonField];
}
メソッドを定義すること-stopObservingButtonField
と-startObservingButtonField
:
- (void)stopObservingButtonField
{
if (mButtonField) {
[mButtonField removeObserver:self
forKeyPath:@"stringValue"
context:&ButtonTextKVOContext];
}
}
- (void)startObservingButtonField
{
if (mButtonField) {
[self.buttonField addObserver:self
forKeyPath:@"stringValue"
options:0
context:&ButtonTextKVOContext];
}
}
この配置の結果として、メソッドmButtonField
の外部に変数を設定してはなりません。-setButtonField:
(これは完全に真実ではありませんが、設定mButtonField
する場合は、まず最初に古い値のキーパスの監視を停止し@"stringValue"
、新しい値の@ "stringValue"キーパスの監視を開始する必要があります。単に呼び出すのではなく、これを行う-setButtonField:
可能性が非常に高くなります。単にコードの繰り返しを構成するだけで、価値はありません。)
参考までに、プロトコルに関するAppleのドキュメントをNSKeyValueObserving
確認してください。