KVO 键值观察,简单来说就是为一个key添加一个观察者,当key的值发生改变的时候会发送通知,在接到通知的时候会有回调方法被调用
#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
时间: 2024-10-11 20:52:59