KVC&KVO

一.KVC

1.KVC即Key-value coding

Key-value coding is a mechanism enabled by the NSKeyValueCoding informal protocol that objects adopt to provide indirect access to their properties

2.默认继承至NSObject都支持这个

In order to make your own objects key-value coding compliant, you ensure that they adopt the NSKeyValueCoding informal protocol and implement the corresponding methods, such as valueForKey: as a generic getter and setValue:forKey: as a generic setter. Fortunately, as described above, NSObject adopts this protocol and provides default implementations for these and other essential methods

3.依赖KVC的技术有下面:

1.Key-value observing

2.Cocoa bindings

3.Core Data

4.AppleScript

常用的有KVO和Core Data

4.常见的用法:

@interface PersonInfoModel : NSObject

@property (nonatomic, strong) NSString *name;

@property (nonatomic, strong) NSString *age;

@property (nonatomic, strong) NSString *address;

@property (nonatomic, strong) NSString *id;

@end

设值:PersonInfoModel *model = [[PersonInfoModel alloc] init];

[model setValue:address forKey:@"address"];

取值: NSString *_address = [model valueForKey:@"address"];

二.KVO

1.KVO即Key-Value Observing

KVO 是 Objective-C 对观察者模式(Observer Pattern)的实现。也是 Cocoa Binding 的基础。当被观察对象的某个属性发生更改时,观察者对象会获得通知。

2.具体用法

基本上都会用,不做具体介绍啦

3.关于实现机制,官方文档有简单提到过

Automatic key-value observing is implemented using a technique called isa-swizzling.

The isa pointer, as the name suggests, points to the object's class which maintains a dispatch table. This dispatch table essentially contains pointers to the methods the class implements, among other data.

When an observer is registered for an attribute of an object the isa pointer of the observed object is modified, pointing to an intermediate class rather than at the true class. As a result the value of the isa pointer does not necessarily reflect the actual class of the instance.

You should never rely on the isa pointer to determine class membership. Instead, you should use the class method to determine the class of an object instance.

简单概述就是:

当你观察一个对象时,一个新的类会动态被创建。这个类继承自该对象的原本的类,并重写了被观察属性的 setter 方法。自然,重写的 setter 方法会负责在调用原 setter 方法之前和之后,通知所有观察对象值的更改。最后把这个对象的 isa 指针 ( isa 指针告诉 Runtime 系统这个对象的类是什么 ) 指向这个新创建的子类,对象就神奇的变成了新创建的子类的实例。

原来,这个中间类,继承自原本的那个类。不仅如此,Apple 还重写了 -class 方法,企图欺骗我们这个类没有变,就是原本那个类。

4.所以用KVO做键值观察后,系统会自动在运行时重写被观察对象属性的setter,类似这样:

  • (void)setName:(NSString *)name { [self willChangeValueForKey:@"name"]; _name = name; [self didChangeValueForKey:@"name"]; }

5.也可以通过以下方法关闭自动键值检测,改为手动实现

关闭自动键值检测:

+ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key

{

if ([key isEqualToString:@"name"]) {

return NO;

}

return YES;

}

手动触发:


- (void)setName:(NSString *)name

{

[self willChangeValueForKey:@"name"];

_name = name;

[self didChangeValueForKey:@"name"];

}

参考链接:
https://www.jianshu.com/p/a8809c1eaecc
http://tech.glowing.com/cn/implement-kvo/

你可能感兴趣的:(KVC&KVO)