KVO Key-Value Observing 它提供一种机制,当指定的对象的属性被修改后,则观察者就会接受到通知!!
观察者可以是对象本身,也可以是其他的类对象!!
使用步骤:
1.注册观察对象的属性!
2.实现观察触发的回调方法!
3.在dealloc中移除观察
下面贴一段测试代码:
创建一个Person类
//.h文件 #import <Foundation/Foundation.h> @interface Person : NSObject @property(nonatomic,copy)NSString *name; @property(nonatomic,assign)float height; @property(nonatomic,strong)NSMutableArray *array; +(Person *)personWithName:(NSString *)aName height:(float)height; @end //.m 文件 #import "Person.h" @implementation Person +(Person *)personWithName:(NSString *)aName height:(float)height { Person *per = [[Person alloc]init]; per.name = aName; per.height = height; per.array = [NSMutableArray arrayWithArray:@[@"zzzXXXzzz"]]; return per; } @end
//在需要用的控制器或者类中 注册观察 _person = [Person personWithName:@"AAA" height:179.5]; [_person addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil]; [_person addObserver:self forKeyPath:@"height" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil]; [_person addObserver:self forKeyPath:@"array" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
//改变观察的属性的值 _person.name = @"BBB";//触发一次观察方法 _person.name = @"CCC";//触发一次观察方法 _person.height = 185;//触发一次观察方法 //这种向数组中添加删除数据不会触发观察方法 [_person.array addObject:@"123"]; [_person.array addObject:@"456"]; [_person.array removeObject:@"123"]; //重新给数组赋值,可以触发观察者方法 _person.array = [@[@"creat",@"a",@"new",@"array"] mutableCopy];
//在注册观察的类中 实现这个观察回调方法
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context { if ([keyPath isEqualToString:@"name"]) { NSLog(@"改变前的值:%@ --- 改变后的值:%@",[change objectForKey:@"old"],[change objectForKey:@"new"]); } if ([keyPath isEqualToString:@"height"]) { //you code NSLog(@"改变前的值:%@ --- 改变后的值:%@",[change objectForKey:@"old"],[change objectForKey:@"new"]); } if ([keyPath isEqualToString:@"array"]) { NSLog(@"改变前的值:%@ --- 改变后的值:%@",[change objectForKey:@"old"],[change objectForKey:@"new"]); } }
//移除观察 -(void)dealloc { [_person removeObserver:self forKeyPath:@"name"]; [_person removeObserver:self forKeyPath:@"height"]; [_person removeObserver:self forKeyPath:@"array"]; }
文章到这已经结束啦,希望对路过的朋友有所帮助!!!