如何确保属性值支持KVC

博客介绍了如何确保属性值支持KVC。KVC是通过key字符串间接访问类属性,途径有setValue:forKeyPath:或valueForKeyPath:。让属性支持KVC需让getter、setter方法和实例变量遵循KVC的key规则,还分别说明了属性为Attribute、To - One Relationship和To - Many Relationship时的实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Make a property KVC Compliant(如何确保属性值支持KVC)

自我感悟:KVC 无非就是通过 key 字符串的方式间接的访问类的属性。访问的途径有 setValue:forKeyPath: 或 valueForKeyPath:。那么如何让属性支持 KVC 呢,无非就是让属性的 getter 方法,setter 方法和实例变量都遵循 KVC 的 key 规则。如 setter 方法为 setKey:,getter 方法为 key or isKey,实例变量为 key or _key。

How you make a property KVC compliant depends on whether that property is an attribute, a to-one relationship, or a to-many relationship. For attributes and to-one relationships, a class must implement at least one of the following in the given order of preference (key refers to the property key)

如何使 property 支持 KVC,取决于 property 是 attribute,还是 to-one relationship,还是 to-many relationship。

Property is Attribute or To-One Relationship

若 property 是 attribute,或 to-one relationship,则必须至少实现以下所列的一种。

  • The class has a declared property with the name key.

    类必须以 key 为名声明属性

  • Implement a method named key or isKey, or create an instance variable key or _key. The compiler typically does this for you when it automatically synthesizes properties.

    类必须要实现 key or isKey 命名的方法,或用 @systhesize 创建实例变量 key or _key。编译器自动合成属性的时候,通常会为你做这些事。

  • If the property is mutable, implement the set: method. The compiler typically does this for you when you allow it to automatically synthesize your properties.

    若 property 是可变的,实现 setKey: 方法。编译器通常在合成属性时,为你自动做这些事情。

  • If the property is a scalar, override the setNilValueForKey: method to gracefully handle the case where a nil value is assigned to the scalar property.

    如果属性是纯量(如 float, int, …),重写 setNilValueForKey: 方法来优雅地处理一个 nil 值付给了一个纯量属性。

Property is To-Many Relationship

Implementing KVC compliance for a to-many relationship is a more complicated procedure.

to-many relationship 支持 KVC 是更加复杂的过程。参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值