:用于數據組件的狀態數據發生改變時,試圖組建能動態更新自己
iOS應用通常會把應用程序組建分開為
數據模型組件:負責維護應用程序的狀態數據
試圖組件:負責顯示數據模型組建內部的狀態數據
addObserver:forKeyPath:options:context:注冊一個監聽器用于監聽指定的Key路徑
removeObserver:forKeyPath:為Key路徑刪除指定的監聽器
removeObserver:forKeyPath:context:為Key路徑刪除指定的監聽器 只是多了一個context參數
context 填入修改時想要顯示的信息
操作:
1.為被監聽對象(通常是數據模型組件)注冊監聽器
2.重寫監聽器的observeValueForKeyPath: ofObject: change: context: 方法
keyPath 被修改的keyPath
object 被修改的對象
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"];
}