KVO 鍵值觀察,簡單來講就是爲一個key添加一個觀察者,當key的值發生改變的時候會發送通知,在接到通知的時候會有回調方法被調用code
#import "ViewController.h" @interface ViewController (){ NSMutableDictionary * myDict; } @end @implementation ViewController - (IBAction)dasdas:(id)sender { //改變key的值 NSString * key = [myDict objectForKey:@"key"]; if ([key isEqualToString:@"key1"]) { [myDict setValue:@"key2" forKey:@"key"]; }else { [myDict setValue:@"key1" forKey:@"key"];; } key = [myDict objectForKey:@"key"]; NSLog(@"%@",key); } - (void)dealloc { //移除觀察者 [myDict removeObserver:self forKeyPath:@"key"]; } - (void)viewDidLoad { [super viewDidLoad]; myDict = [[NSMutableDictionary alloc] init]; [myDict setValue:@"key1" forKey:@"key"]; //添加觀察者 [myDict addObserver:self forKeyPath:@"key" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } //觀察者觀察的對象發生改變的時候調用的方法 - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if ([keyPath isEqualToString:@"key"]) { NSString * key = [(NSDictionary *)object objectForKey:@"key"]; if ([key isEqualToString:@"key1"]) { self.view.backgroundColor = [UIColor greenColor]; }else { self.view.backgroundColor = [UIColor orangeColor]; } } } @end