KVO
2017-03-08 本文已影响0人
March_Cullen
- 让一个对象监听另一个对象属性的改变
// MJPerson.h
#import <Foundation/Foundation.h>
@interface MJPerson : NSObject
@property(nonatomic, assign)NSInteger age;
@end
// MJPerson.m
@implementation MJPerson
@end
// MJDog.h
#import <Foundation/Foundation.h>
@interface MJDog : NSObject
@end
// MJDog.m
#import “MJDog.h”
@implementation MJDog
@end
// MJViewController.h
#import <Foundation/Foundation.h>
@interface MJViewController : UIViewController
@end
// MJViewController.m
#import “MJViewController.h”
#import “MJPerson.h”
#import “MJDog”
@interface MJViewController () // 这是类扩展,类别的一种
@property (nonatomic, strong)MJPerson *person;
@property (nonatomic, strong)MJDog *dog;
@end
@implementation MJViewController
- (void)viewDidLoad {
self.person = [[MJPerson alloc] init];
self.dog = [[MJDog alloc] init];
// 让self.dog监听self.person的age属性的改变
[self.person addObsever:self.dog forKeyPath:@”age” options:0 context:nil];
}
- (void)touchesBegan:(NSSet *)touches withEvents:(UIEvent *)event {
self.person.age = 30;
}
@end
KVO内部实现原理
运行过程中,系统会自动生成一个NSKVONortifying_MJPerson :MJPerson
类,调用person的setAge
方法,会调用子类的setAge
方法,runtime中会使用到KVO。
// NSKVONortifying_MJPerson.h
#import “MJPerson.h”
@interface NSKVONortifying_MJPerson : MJPerson
@end
// NSKVONortifying_MJPerson.m
#import “NSKVONortifying_MJPerson.h”
@implementation NSKVONortifying_MJPerson
- (void)setAge:(int)age {
[super setAge:age];
[self willChangeValueForKey:@”age”];
[self didChangeValueForKey:@”age”];
}
@end