如果我想编写自己的符合 KVO 的 setter 方法,它会看起来像这样吗?
- (void)setFirstName:(NSString*)firstNameValue {
[self willChangeValueForKey:@"firstName"];
[firstName release];
firstName = firstNameValue;
[firstName retain];
[self didChangeValueForKey:@"firstName"];
}
是这样吗?那么 willChange... foobar didChange... 块会导致 KVO 通知触发吗?
- (void)setFirstName:(NSString*)firstNameValue {
[self willChangeValueForKey:@"firstName"];
[firstName release];
firstName = firstNameValue;
[firstName retain];
[self didChangeValueForKey:@"firstName"];
}
Is that right? So the willChange... foobar didChange... block causes an KVO notification to fire?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,您的实施并非 100% 正确。想象一下,如果当前将firstName设置为NSString实例并且使用该相同实例调用setter,会发生什么。首先,您将释放实例,然后设置实例变量,在这种情况下不会更改任何内容,然后您尝试保留实例,但到那时它很可能已经被释放。
它应该是:
或:
后一个版本还有一个额外的优点,即如果值没有真正更改,则不会发送oberserver-notifications。
No, your implementation is not 100% correct. Think what happens if the firstName is currently set to a NSString-instance and the setter is called with that very same instance. First you will release the instance, than you will set the instance variable, which in this case dosen't change anything and than you try the retain the instance, but by that time it could very well been dealloced already.
It should be:
or:
The latter version has the additional advantage of not sending oberserver-notifications if the value is not really changed.
是 - 调用
didChangeValueForKey:
将通知所有观察者该值已更改。Yes - calling
didChangeValueForKey:
will notify all the observers that the value has changed.