UI进阶之网络进阶KVO

引入框架

#import
"ViewController.h" #import <CommonCrypto/CommonCrypto.h> @interface ViewController () //添加数组属性 @property (nonatomic, strong) NSMutableArray *array; @end @implementation ViewController #warning ---重中之重--- //移除观察者 - (void)dealloc { //只要使用KVO 那就一定要写这个移除观察者的方法 [self removeObserver:self forKeyPath:@"array"]; } - (void)viewDidLoad { [super viewDidLoad]; //谁去观察谁的哪一个属性,检查它变化的时间 //添加一个观察者 //第一个self 表示观察者 //第一个参数: 被观察者 //第二个参数: 哪一个属性被观察 //第三个参数: 什么时候触发观察者方法 //第四个参数: 保险, 可以添加一些字符串 self.array = [NSMutableArray array]; [self addObserver:self forKeyPath:@"array" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil]; } - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { NSArray *array = @[@"1", @"2"]; //[self.array setArray:array]; //KVC的方法 [[self mutableArrayValueForKeyPath:@"array"]setArray:array]; } //观察者模式触发的方法 - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context { NSLog( @"keypath == %@", keyPath); NSLog(@"object == %@", object); NSLog(@"change == %@", change); }

 

posted @ 2016-04-07 20:50  胡一波  阅读(110)  评论(0编辑  收藏  举报