KVC setNilValueForKey:建议调用方法,而不使用属性访问器 [英] KVC setNilValueForKey: recommends calling method and not using property accessor

查看:939
本文介绍了KVC setNilValueForKey:建议调用方法,而不使用属性访问器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

KVC文档


当您尝试将属性设置为nil时,将调用键值编码方法setNilValueForKey: $ b

The key-value coding method setNilValueForKey: method is called when you attempt to set an attribute to nil.

到目前为止听起来不错


...使用setValue:forKey :设置新值。这保持了模型的封装,并确保实际上会发生由于设置值而应该发生的任何附加动作。 这是比调用访问器方法或直接设置实例变量更好的做法。

更好的做法是在 -setNilValueForKey:方法中调用 -setValue:forKey:原始或值类型属性?使用KVC方法是否有性能或技术优势 -setValue:forKey:与属性访问器相反(我假设当访问器方法适用于访问器属性,因为他们只是合成糖的方法)?通常当Apple建议一个最佳实践时,有一个性能或可靠性问题支持它。有人知道有记录的原因为什么

Why is it better practice to call the -setValue:forKey: inside the -setNilValueForKey: method when setting a 'default' value on a primitive or value type property? Is there a performance or technical advantage to using the KVC method -setValue:forKey: opposed to the property accessor (I'm assuming that when it says accessor method it applies to accessor properties as well since they're just syntatic sugar over the method)? Usually when Apple recommends a 'best practice' there is a performance or reliability concern backing it. Does anybody know a documented reason why?

推荐答案

从您的报价:


这维护了模型的封装,并确保实际上会发生由于设置值而发生的任何其他操作。

This maintains encapsulation of the model and ensures that any additional actions that should occur as a result of setting the value will actually occur.

调用 setValue:forKey:而不是访问器或更改ivar可确保维持所有正确的副作用。当报价提到维护封装时,它意味着停留在KVC方法而不是定制访问器。调用 setValue:forKey:也意味着你得到运行时来决定如何为你设置属性。最后,附加动作可能指的是键值观察。它将确保正确的方法被调用,而不是任何不应该被调用。

Calling setValue:forKey: instead of an accessor or changing the ivar ensures that all proper side effects are maintained. When the quote mentions maintaining encapsulation, it means staying in KVC methods instead of custom accessors. Calling setValue:forKey: also means that you get the runtime to decide how the property should be set for you. Finally, the "additional actions" is probably referring to key-value observing. It will make sure the right methods are called, and not any that shouldn't be called.

这篇关于KVC setNilValueForKey:建议调用方法,而不使用属性访问器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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