KVC setNilValueForKey: recommends calling method and not using property accessor

﹥>﹥吖頭↗ 提交于 2019-12-10 16:27:27

问题


The KVC Documentation says

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

Sounds good so far

... uses setValue:forKey: to set the new value. 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. This is considered better practice than calling an accessor method or setting an instance variable directly.

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?


回答1:


From your quote:

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.

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.



来源:https://stackoverflow.com/questions/6480432/kvc-setnilvalueforkey-recommends-calling-method-and-not-using-property-accessor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!