Search code examples
iosswiftcocoakey-value-coding

In Swift, is Key-Value Coding available for custom objects without subclassing NSObject?


In Key-Value Coding Programming Guide it states NSObject subclasses are KVC compliant.

Swift objects that inherit from NSObject or one of its subclasses are key-value coding compliant for their properties by default

Can custom objects(struct, classes) adopt NSKeyValueCoding and be KVC compliant? Also, how is KVC given to an object just by subclassing NSObject?


Solution

  • Unlike a formal protocol, that any object could technically conform to, NSKeyValueCoding is available to any NSObject via Informal Protocols:

    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.

    This is as opposed to simply implementing the KVC directly into NSObject, I think the main benefit of the informal protocol is to split up the functionality of NSObject into separate files. But there may be other benefits of using Informal Protocols

    And because NSKeyValueCoding is a category on NSObject, you unfortunately cannot just make any custom object support KVC