ViewController.m#
//
// ViewController.m
// KVO
//
//
#import "ViewController.h"
#import "Person.h"
@interface ViewController ()
@property(nonatomic, strong)Person *person;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.person = [[Person alloc] init];
_person.name = @"dongliang";
//添加觀察者 注冊
[_person addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:(__bridge void *)self];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
[self.view addGestureRecognizer:tap];
}
//觀察者的方法
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
//keypath 是觀察的屬性
NSLog(@"---------keypath:%@",keyPath);
//被觀察的對象
NSLog(@"---------object:%@",object);
//新舊值
NSLog(@"---------change:%@",change);//change是字典
NSLog(@"---------context:%@",context);
if ([change[NSKeyValueChangeNotificationIsPriorKey]boolValue]) {
NSLog(@"1");
NSLog(@"值改變之前");
} else{
NSLog(@"2");
NSLog(@"值改變之后");
}
// self.view.backgroundColor = [UIColor greenColor];
//context的作用就是傳值/////////////////////////////
ViewController *vc = (__bridge ViewController *)context;
vc.view.backgroundColor = [UIColor greenColor];
}
-(void)tapAction:(UITapGestureRecognizer *)sender{
//我注意你很久了
_person.name = @"zhaoyu";
}
/**
* 移除觀察者!!!!!!!!!!!!!!!!!
*/
-(void)dealloc{
[_person removeObserver:self forKeyPath:@"name"];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
Person.h#
//
// Person.h
// KVO
//
//
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property(nonatomic, strong)NSString *name;
@end
Person.m#
//
// Person.m
// KVO
//
//
#import "Person.h"
@implementation Person
@end
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者