美文网首页iOS开发iOS DeveloperIOS
Key-Value Coding Programming Gui

Key-Value Coding Programming Gui

作者: 花与少年_ | 来源:发表于2017-07-31 00:41 被阅读58次

KVC

需要遵从协议 NSKeyValueCoding , NSObject 遵从此协议,实现协议方法,所以大多数 NSObject 的子类不必重写这两个方法:

- (id)valueForKey:(NSString *)key;
- (void)setValue:(nullable id)value forKey:(NSString *)key;
  • valueForKey: 取定义过的key值
    特别的是,在容器类上调用此方法,会将消息传递给容器类中的每一个对象,而不是对容器本身进行操作。
  • valueForUndefinedKey: 取未定义的key值
    未重写此方法时,易导致NSUnknownKeyException错误

key 与 keyPath 的区别

A key is a string that identifies a specific property.

A key path is a string of dot-separated keys used to specify a sequence of object properties to traverse.

给基本类型的属性置 nil,程序会崩溃引发 NSInvalidArgumentException 异常。

重写- (void)setNilValueForKey:(NSString *)key 方法避免异常。

A collection operator is one of a small list of keywords preceded by an at sign (@) that specifies an operation that the getter should perform to manipulate the data in some way before returning it.

Search Pattern for the Basic Getter

对于setValue:属性值 forKey:@"name";代码,底层的执行机制如下:

(1).程序优先调用“setName:属性值;”代码通过setter方法完成设置。

(2).如果该类没有setName:方法,KVC机制会搜索该类名为name的成员变量,找到后对name成员变量赋值。

(3).如果该类既没有setName:方法,也没有定义_name成员变量,KVC机制会搜索该类名为name的成员变量,找到后对name成员变量赋值。

(4).如果上面3条都没有找到,系统将会执行该对象的setValue: forUndefinedKey:方法。默认setValue: forUndefinedKey:方法会引发一个异常,将会导致程序崩溃。

对于“valueForKey:@"name";”代码,底层执行机制如下:

(1).程序优先调用"name;"代码来获取该getter方法的返回值。

(2).如果该类没有name方法,KVC机制会搜索该类名为name的成员变量,找到后返回name成员变量的值。

(3).如果该类既没有name方法,也没有定义_name成员变量,KVC机制会搜索该类名为name的成员变量,找到后返回name成员变量的值。

(4).如果上面3条都没有找到,系统将会执行该对象的valueForUndefinedKey:方法。默认valueForUndefinedKey:方法会引发一个异常,将会导致程序崩溃。

Adopting Key-Value Coding

Using a @propertystatement, allowing the compiler to automatically synthesize the ivar and accessors.

@property 自动为属性配置get、set方法

Normally, the compiler does this for you when automatically synthesizing properties, but if you use an explicit @synthesize directive, you can enforce this naming yourself:

@synthesize 为属性配置名字

@synthesize title = _title;

use a @dynamic directive to inform the compiler that you will provide getters and setters at runtime.

@dynamic 为属性动态提供get、set方法

When the property is a scalar or a structure, the default implementation of key-value coding wraps the value in an object for use on the protocol method’s interface

参考文章:
iOS 之键值编码(KVC)与键值监听(KVO)

相关文章

网友评论

    本文标题:Key-Value Coding Programming Gui

    本文链接:https://www.haomeiwen.com/subject/udhllxtx.html