KVO
通過kvc的方式修改被觀察者的屬性時 主動通知觀察者
注冊observing對象addObserver:forKeyPath:options:context:委托代理觀察者類必須重寫方法?observeValueForKeyPath:ofObject:change:context:
kvo是同步的
應用場景:
MVC模型中,數據庫(dataModal)發生變化時,引起view改變,用這種方式實現非常方便代碼:
新建model person
@interface Person : NSObject @property (nonatomic, assign) int age; +(instancetype)personWithDict:(NSDictionary *)dict; @end +(instancetype)personWithDict:(NSDictionary *)dict { id obj = [[self alloc]init]; [obj setValuesForKeysWithDictionary:dict]; return obj; }- (void)viewDidLoad { [super viewDidLoad]; self.person = [Person personWithDict:@{@"age":@(100)}]; /* 1.誰進行觀察 2.觀察哪個屬性 3.觀察者的選項 4.場景 可以根據監聽時來判斷 */ [self.person addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew context:nil]; }
//添加監聽后 一旦監聽到更改會調用此方法 -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context { NSLog(@"keypath:%@ obj:%@ change:%@ context:%@",keyPath,object,change,context); } -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { self.person.age = self.person.age -1; NSLog(@"%d",self.person.age); }
轉載于:https://www.cnblogs.com/fucker/articles/5028935.html
總結
- 上一篇: 2-字节流
- 下一篇: LAMP 2.2 Apache配置静态