笔记03 KVO & KVC

2021-03-11  本文已影响0人  PPFSaber

二 KVO key-value-observe
MJPerson的 instance 对象 添加 kvo 的时候 会动态派生出一个 新的类 类似 NSKOVNotifying_MJPerson 的类 和 一个 NSKOVNotifying_MJPerson meta-class(元类)
instance 对象 的isa 指针 会指向 NSKOVNotifying_MJPerson 对象
NSKOVNotifying_MJPerson class 对象的 isa。指向 NSKOVNotifying_MJPerson meta-class 元类
NSKOVNotifying_MJPerson 是 MJPerson的 子类 会重写 监听 的key 的set 方法 class 方法 dealloc 方法 iskvo方法

类似 下边的情况
@implementation NSKVONotifying_MJPerson

// 伪代码
void _NSSetIntValueAndNotify()
{
[self willChangeValueForKey:@"age"];
[super setAge:age];
[self didChangeValueForKey:@"age"];
}

@end

三 KVC

1 直接修改 实例变量的值不会调用 [oberser observeValueForKeyPath:key ofObject:self change:nil context:nil];
2 setValue:forKey: 会调用 [oberser observeValueForKeyPath:key ofObject:self change:nil context:nil];

setValue:forKey:
以 [stuedent setValue:@10 forKey:@“age”]; 为例
执行方式是
1 搜索 setAge 、 _setAge
2 如果都没有 则 调用 + (BOOL)accessInstanceVariablesDirectly 如果允许直接访问实例变量 则 依次 搜索 _age、_isAge 、 isAge、age 如果搜索到则赋值(会调用 observeValueForKeyPath)

getValueForKey:
以 [stuedent getValue:ForKey:@“age”]; 为例
1 依次搜索 getAge 、 _getAge、isAge、_isage 有则调用
2 如果都没有 则 调用 + (BOOL)accessInstanceVariablesDirectly 如果允许直接访问实例变量 则 依次 搜索 _age、_isAge 、 isAge、age 如果搜索到则调用.

上一篇 下一篇

猜你喜欢

热点阅读