在 Swift 中,Key-Value Coding 是否可用于自定义对象而无需子类化 NSObject?
In Swift, is Key-Value Coding available for custom objects without subclassing NSObject?
在 Key-Value Coding Programming Guide 中声明 NSObject sub类 符合 KVC。
Swift objects that inherit from NSObject or one of its subclasses are key-value coding compliant for their properties by default
自定义对象 (struct, 类) 能否采用 NSKeyValueCoding
并符合 KVC 标准?
另外,如何仅通过子类化 NSObject 将 KVC 赋予对象?
与任何对象在技术上都可以遵守的正式协议不同,NSKeyValueCoding
通过 Informal Protocols:
可用于任何 NSObject
An informal protocol is a category on NSObject, which implicitly makes
almost all objects adopters of the protocol. (A category is a language
feature that enables you to add methods to a class without subclassing
it.) Implementation of the methods in an informal protocol is
optional. Before invoking a method, the calling object checks to see
whether the target object implements it. Until optional protocol
methods were introduced in Objective-C 2.0, informal protocols were
essential to the way Foundation and AppKit classes implemented
delegation.
这与直接将 KVC 直接实现到 NSObject
不同,我认为非正式协议的主要好处是将 NSObject
的功能拆分到单独的文件中。但是使用非正式协议可能还有其他好处
并且由于 NSKeyValueCoding
是 NSObject
上的一个类别,很遗憾,您不能只让任何自定义对象支持 KVC
在 Key-Value Coding Programming Guide 中声明 NSObject sub类 符合 KVC。
Swift objects that inherit from NSObject or one of its subclasses are key-value coding compliant for their properties by default
自定义对象 (struct, 类) 能否采用 NSKeyValueCoding
并符合 KVC 标准?
另外,如何仅通过子类化 NSObject 将 KVC 赋予对象?
与任何对象在技术上都可以遵守的正式协议不同,NSKeyValueCoding
通过 Informal Protocols:
NSObject
An informal protocol is a category on NSObject, which implicitly makes almost all objects adopters of the protocol. (A category is a language feature that enables you to add methods to a class without subclassing it.) Implementation of the methods in an informal protocol is optional. Before invoking a method, the calling object checks to see whether the target object implements it. Until optional protocol methods were introduced in Objective-C 2.0, informal protocols were essential to the way Foundation and AppKit classes implemented delegation.
这与直接将 KVC 直接实现到 NSObject
不同,我认为非正式协议的主要好处是将 NSObject
的功能拆分到单独的文件中。但是使用非正式协议可能还有其他好处
并且由于 NSKeyValueCoding
是 NSObject
上的一个类别,很遗憾,您不能只让任何自定义对象支持 KVC