何时使用"willChangeValueForKey"和"didChangeValueForKey"? [英] when to use "willChangeValueForKey" and "didChangeValueForKey"?

查看:349
本文介绍了何时使用"willChangeValueForKey"和"didChangeValueForKey"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在演示项目中看到了这些行,但是我不明白为什么这么做.

I saw these lines in a demo project, but I couldn't understand why it did that.

[self willChangeValueForKey:@"names"];
[self didChangeValueForKey:@"names"];

它将在willChangeeValueForKey之后立即调用didChangeValueForKey. 有道理吗?

It called didChangeValueForKey immediately after willChangeeValueForKey. Does it make any sense?

此外,什么时候该调用这两个方法? 非常感谢!! :)

Furthermore, when should be the right time to call this two methods? Thanks a lot!! :)

推荐答案

实际上,这是一种反模式.在未进行任何实际属性更改的情况下,您不应调用-willChangeValueForKey:,后接-didChangeValueForKey:.在某些情况下,这样做可能掩盖代码中其他地方的KVO问题,并迫使观察者更新与所讨论属性有关的状态.但是,最终,您(或您引用的示例的作者)应该修复其余的代码,以便不需要此反模式.

This is, in fact, an anti-pattern. You should not call -willChangeValueForKey: followed by -didChangeValueForKey: without any intervening actual property change. In some cases, doing so can mask KVO problems elsewhere in your code and force observers to update their state related to the property in question. Ultimately, however, you (or the author of the example you cite) should fix the rest of the code so that this anti-pattern is unnecessary.

-will|didChangeValueForKey:的正确用法是在修改属性时未使用兼容KVC的访问器/设置器,以使KVO机制不会注意到更改.对于一个人为的示例,请考虑直接为属性修改后备实例变量:

The correct usage of -will|didChangeValueForKey: is when you are modifying a property without using KVC-compliant accessors/setters such that the KVO mechanism would not notice the change. For a contrived example, consider modifying the backing instance variable for an attribute directly:

@interface Foo
{
   int bar;
}
@end

@implementation Foo
- (void)someMethod
{
  bar = 10;
}
@end

bar属性中注册了更改通知的

KVO观察者不会在-someMethod中接收到对bar更改的通知.要使KVO机械正常工作,您可以修改-someMethod:

KVO observers that had registered for notification of changes in the bar property would not recieve notification of the change to bar in -someMethod. To make the KVO machinery work, you could modify -someMethod:

- (void)someMethod
{
  [self willChangeValueForKey:@"bar"];
  bar = 10;
  [self didChangeValueForKey:@"bar"];
}

当然,最好使用@property声明并使用符合KVC的访问器/设置器(手动编码或@synthesized),但这是一个人为的示例.

Of course, it would be better to use a @property declaration and to use KVC-compliant accessors/setters (either manually coded or @synthesized), but this is a contrived example.

这篇关于何时使用"willChangeValueForKey"和"didChangeValueForKey"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆