gpt4 book ai didi

ios - 在 Swift 中,键值编码是否可用于自定义对象而无需子类化 NSObject?

转载 作者:可可西里 更新时间:2023-11-01 01:20:15 25 4
gpt4 key购买 nike

Key-Value Coding Programming Guide它声明 NSObject 子类符合 KVC。

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

自定义对象(结构、类)是否可以采用 NSKeyValueCoding 并符合 KVC 标准?另外,如何仅通过子类化 NSObject 将 KVC 赋予对象?

最佳答案

与任何对象在技术上都可以遵守的正式协议(protocol)不同,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 中不同,我认为非正式协议(protocol)的主要好处是将 NSObject 的功能拆分到单独的文件中.但是使用非正式协议(protocol)可能还有其他好处

而且因为 NSKeyValueCodingNSObject 上的一个类别,不幸的是你不能让任何自定义对象都支持 KVC

关于ios - 在 Swift 中,键值编码是否可用于自定义对象而无需子类化 NSObject?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44268963/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com