objective-c - KVC setNilValueForKey : recommends calling method and not using property accessor

标签 objective-c ios cocoa key-value-coding

KVC Documentation

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/

相关文章:

objective-c - 导入并包含在头文件中 - 什么时候可以?

ios - iPhone6 +在模拟器上呈现736点宽,但在实际设备上呈现667点宽

objective-c - 为 NSView 的 NSTextFields 设置标签顺序

objective-c - 从 std::string 转换为 NSString

ios - 屏幕分辨率

objective-c - 用户接受后,iRate 会自动停止征求评论吗?

cocoa - Xcode 3.2.2 拒绝打开任何项目文件夹?

ios - XCUITest:在 TableView 中查找 CollectionView 失败

ios - 如何检查两个 NSDate 之间的时间量?

ios - build设置中的 "Objective-C Bridging Header"条目未出现在 Xcode 8.3 中