:用于數(shù)據(jù)組件的狀態(tài)數(shù)據(jù)發(fā)生改變時(shí),試圖組建能動(dòng)態(tài)更新自己
iOS應(yīng)用通常會(huì)把應(yīng)用程序組建分開為
數(shù)據(jù)模型組件:負(fù)責(zé)維護(hù)應(yīng)用程序的狀態(tài)數(shù)據(jù)
試圖組件:負(fù)責(zé)顯示數(shù)據(jù)模型組建內(nèi)部的狀態(tài)數(shù)據(jù)
addObserver:forKeyPath:options:context:注冊(cè)一個(gè)監(jiān)聽器用于監(jiān)聽指定的Key路徑
removeObserver:forKeyPath:為Key路徑刪除指定的監(jiān)聽器
removeObserver:forKeyPath:context:為Key路徑刪除指定的監(jiān)聽器 只是多了一個(gè)context參數(shù)
context 填入修改時(shí)想要顯示的信息
操作:
1.為被監(jiān)聽對(duì)象(通常是數(shù)據(jù)模型組件)注冊(cè)監(jiān)聽器
2.重寫監(jiān)聽器的observeValueForKeyPath: ofObject: change: context: 方法
keyPath 被修改的keyPath
object 被修改的對(duì)象
change 被修改的屬性值
context 被修改的上下文 add 方法中的context
-(void)setP:(FKPreson *)p{
_p=p;
[self.p addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:@"my name"];
[self.p addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew context:@"my age"];
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
NSLog(@"_____________我是華麗的分割線________________");
NSLog(@"%@",keyPath);
NSLog(@"%@",object);
NSLog(@"%@",change);
NSLog(@"%@",context);
}
-(void)dealloc{
[self.p removeObserver:self forKeyPath:@"name"];
[self.p removeObserver:self forKeyPath:@"age"];
}