KVC/KVO
- 添加觀察者
self.person = [[Person alloc]init]; self.person.name = @"EZ"; //為self.person 添加觀察者self,當self.person的name屬性發(fā)生改變時坊秸,觀察者方法將被調用 //所以必須要實現 observeValueForKeyPath:ofObject:change:context: 方法(觀察者方法) //options:監(jiān)聽它的新值和舊值(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld) [self.person addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
- KVC賦值麸祷,觸發(fā)KVO
//使用kvc給self.person的name屬性賦值,只有使用kvc賦值褒搔,才會觸發(fā)kvo [self.person setValue:@"Teemo" forKey:@"name"];
- KVO觸發(fā)阶牍,響應方法(實現該方法)
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void *)context { //通過keyPath判斷是監(jiān)聽的哪個屬性值發(fā)生了變化 if ([keyPath isEqualToString:@"name"]) { /** 參數change:改變的屬性的相關信息 新值:change[@"new"] 舊值:change[@"old"] */ NSLog(@"change = %@",change); } } ```
- 移除通知
//為self.person 移除對name屬性的觀察者self,當self.person的
name屬性發(fā)生改變時不再響應self的KVO方法
[self.person removeObserver:self forKeyPath:@"name"];
```
通 知
- 注冊通知
//注冊名字叫做@"TEST"的通知 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(Test:) name:@"TEST" object:nil];
- 實現通知調用方法(注冊時選擇的Test:方法)
//收到notify通知,將調用該方法
-(void)Test:(NSNotification *)notification
{
DLog(@"test = %@",notification.userInfo);
self.notifyLabel.text = [NSString stringWithFormat:@"notify新值 = %@",notification.object[@"name"]];
}
```
3.發(fā)送通知(隨便在哪里發(fā)送星瘾,只要注冊了走孽,這個對象還在,沒有移除注冊通知琳状,就能收到)
//發(fā)送通知 [[NSNotificationCenter defaultCenter] postNotificationName:@"TEST" object:nil userInfo:dic];
- 移除注冊通知
//移除self注冊的通知 [[NSNotificationCenter defaultCenter] removeObserver:self];