【问题标题】:KVO NSKeyValueObservingKVO NSKeyValueObserving
【发布时间】:2014-03-23 02:33:23
【问题描述】:

我想为自定义类的 NSString 进行观察。

//添加

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

//删除

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

在应用程序代表我使用

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

但我不明白,为什么?如何获取对象的新参数?

【问题讨论】:

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


    【解决方案1】:

    您需要使用observeValueForKeyPath 而不是didChangeValueForKey。以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];
    }
    

    【讨论】:

    • 如果它不起作用,那么您实际上需要为属性更改生成一些 KVO 通知。调用 -[NSObject willChangeValueForKey:]-[NSObject didChangeValueForKey:] 看看是否可以解决问题。
    • @Merlevede,我创建 [self addObserver:self forKeyPath:@"messageVC.user.uJid" options:0 context:nil];在属性 messageVC 的 mapVC 中,但后来我得到了 observeValueForKeyPath。然后我将 observeValueForKeyPath 移动到 appDelegate 我没有得到它 [self addObserver:[self appDelegate] forKeyPath:@"messageVC.user.uJid" options:0 context:nil];在mapVC中
    • 错误出现在第一个self,你不是在给self添加观察者,而是在你的mapVC上,所以你应该用你的mapVC实例替换self
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多