用法
KVO鍵值觀察,使用起來非常方便
舉個例子:比如你想要再某個值改變的時候執行一個方法(每次改變都要執行)
你只需要坐到以下兩點即可:
給某對象添加觀察者
[某對象 addObserver:self forKeyPath:@"你要觀察的屬性名" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];實現回調方法,該方法在你所觀察的值改變的時候會觸發
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
示例代碼
#import <UIKit/UIKit.h>
@interface YYListView : UIView<UITableViewDataSource,UITableViewDelegate>
//該屬性設為要觀察的值
@property (nonatomic, assign) NSInteger index;
@end
//在控制器中創建一個YYListView的對象,給它添加觀察者
- (void)viewDidLoad{
[super viewDidLoad];
YYListView *LV = [YYListView alloc]init];
[LV addObserver:self forKeyPath:@"index" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
//每當值改變就調用action方法
[ self action];
}