KVO
通過kvc的方式修改被觀察者的屬性時(shí) 主動通知觀察者
注冊observing對象addObserver:forKeyPath:options:context:委托代理觀察者類必須重寫方法?observeValueForKeyPath:ofObject:change:context:
kvo是同步的
應(yīng)用場景:
MVC模型中,數(shù)據(jù)庫(dataModal)發(fā)生變化時(shí),引起view改變,用這種方式實(shí)現(xiàn)非常方便代碼:
新建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.誰進(jìn)行觀察 2.觀察哪個(gè)屬性 3.觀察者的選項(xiàng) 4.場景 可以根據(jù)監(jiān)聽時(shí)來判斷 */ [self.person addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew context:nil]; }
//添加監(jiān)聽后 一旦監(jiān)聽到更改會調(diào)用此方法 -(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); }
轉(zhuǎn)載于:https://www.cnblogs.com/fucker/articles/5028935.html
總結(jié)
- 上一篇: 2-字节流
- 下一篇: LAMP 2.2 Apache配置静态