KVO - 觀察自定義屬性值

1 . 聲明屬性&註冊監聽ui

{ BOOL isOk; }spa

 

[self addObserver:self forKeyPath:@"isOk" options:0 context:nil];server

 

2 .改變屬性值string

 

[self willChangeValueForKey:@"isOk"]; it

// 只有本身去定義時才須要如此設置 io

isOk = isOk?NO:YES;class

[self didChangeValueForKey:@"isOk"];object

 

3 . 監聽值改變word

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {di

if ([keyPath isEqualToString:@"isOk"]) {

NSLog(@"%d currentThread:%f",isOk,[NSThread currentThread]);

} else { // 必定要調用

[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];

}

}

相關文章
相關標籤/搜索