(这是我在这里学到的一种技术: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;
}