KVO NSKeyValueObserving

时间:2014-03-23 02:33:23

标签: ios objective-c cocoa-touch uiviewcontroller key-value-observing

我想制作Observing for Custom class的NSString。

//添加

[self.sourceUser addObserver:[self appDelegate] forKeyPath:@"uJid" options:0 context:nil];

//删除

[self.sourceUser removeObserver:[self appDelegate] forKeyPath:@"uJid" context:nil];

在app Delegate中我使用

- (void)didChangeValueForKey:(NSString *)key
{
    if ([key isEqualToString:@"uJid"])
    {
       //     self.iHopeItTemp = object       
    }
}

但我没理解,为什么?如何获取对象的新参数?

1 个答案:

答案 0 :(得分:1)

而不是didChangeValueForKey您需要使用observeValueForKeyPath。请查看documentation以获取示例。

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context {

    if ([keyPath isEqual:@"uJid"]) {
        // your code
    }
    /*
     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];
}
相关问题