(これは私がここで学んだテクニックです:http://www.bit-101.com/blog/?p = 1999)
次のように、「コンテキスト」でメソッドを渡すことができます。
[theObject addObserver:self
forKeyPath:@"myKeyPath"
options:NSKeyValueObservingOptionNew
context:@selector(doSomething)];
..次に、observeValueForKeyPathメソッドで、それをSELセレクタータイプにキャストしてから実行します。
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
SEL selector = (SEL)context;
[self performSelector:selector];
}
doSomethingメソッドにデータを渡したい場合は、次のように「change」ディクショナリの「new」キーを使用できます。
[theObject addObserver:self
forKeyPath:@"myKeyPath"
options:NSKeyValueObservingOptionNew
context:@selector(doSomething:)]; // note the colon
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
SEL selector = (SEL)context;
// send the new value of observed keyPath to the method
[self performSelector:selector withObject:[change valueForKey:@"new"]];
}
-(void)doSomething:(NSString *)newString // assuming it's a string
{
label.text = newString;
}