The key-value coding method setNilValueForKey: method is called when you attempt to set an attribute to nil.
目前还不错
... 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.
为什么在 -setNilValueForKey:
方法中调用 -setValue:forKey:
是更好的做法,当在基元或值类型属性上设置“默认”值时?使用 KVC 方法 -setValue:forKey:
相对于属性访问器是否有性能或技术优势(我假设当它说访问器方法时它也适用于访问器属性,因为它们'只是方法上的合成糖)?通常当 Apple 推荐“最佳实践”时,会有性能或可靠性问题支持它。有没有人知道有记录的原因为什么?
最佳答案
来自您的报价:
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:
还意味着您可以让运行时来决定应该如何为您设置属性。最后,“附加操作”可能指的是键值观察。它将确保调用正确的方法,而不是任何不应调用的方法。
关于objective-c - KVC setNilValueForKey : recommends calling method and not using property accessor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6480432/