你需要调用willChangeValueForKey:和didChangeValueForKey:? [英] Do you need to call willChangeValueForKey: and didChangeValueForKey:?

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

问题描述

我认为自煮熟的@property设置应该是这样:

I thought home-cooked @property setters were supposed to look like this:

-(void) setFoo:(Foo *)newFoo {

  // Safeguards 
  // ...

  [self willChangeValueForKey:@"foo"];
  // Switcheroo
  // ...
  [self didChangeValueForKey:@"foo"];
}

但是我看到很多博客文章中的代码做可可太多比我有,这是这样的:

But I see a lot of code in blog posts by people who've been doing Cocoa a lot longer than I have, where it's like this:

-(void) setFoo(Foo *)newFoo {

  // Safeguards 
  // ...

  // Switcheroo
  // ...
}

所以我的问题是,我们需要调用KVO通知方法吗?

So my question is, do we need to call the KVO-notification methods? Or is it being done magically when you update the private iVar, if you're using the modern runtime?

推荐答案

这是神奇的做法除非您选择停用。阅读本节的KVO指南。注意,KVC / KVO存在于从古至今(即在引入 @property 之前),因此设置器 @synthesize d或不。它甚至不涉及旧/新运行时二分法。

It's done magically unless you opt-out. read this section of the KVO guide. Note that KVC/KVO existed from time immemorial (i.e. before the introduction of @property) so it doesn't matter whether the setter is @synthesized or not. It's not even related to the old/new runtime dichotomy.

这个魔法(isa-swizzling)的细节在博文。这是魔法。基本上,当观察到一个键时,运行时会自动替换setter的实现,以便调用KVO通知。

The detail of this magic (isa-swizzling) was detailed in a blog post by Mike Ash. It's magic. Basically, when a key is observed, the runtime automagically replaces the implementation of the setter so that it calls the KVO notification.

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

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