iOS KVO(键-值观察) 的使用总结

来源:互联网 发布:中国网络为什么多喷子 编辑:程序博客网 时间:2024/06/08 15:27

KVO(键-值观察)

// 1.键-值观察 
// 2.它提供一种机制,当指定的对象的属性被修改后,则对象就会接受到通知。 
// 3.符合KVC(Key-ValuedCoding)机制的对象才可以使用KVO 
// 4.实现过程 
// ①注册,指定被观察者 
// ②实现回调方法 
// ③移除观察
代码片段:
- (void)viewDidLoad
{
    [superviewDidLoad];
    // Do any additional setup after loading the view from its nib.
    // 实例化一个观察者对象
    self.stockForKVO= [[StockDataalloc]init];
    // 初始化
    [self.stockForKVOsetValue:@"searph"forKey:@"stockName"];// KVC
    [self.stockForKVOsetValue:@"10.0"forKey:@"price"];// KVC
     
    // 监听并显示在 lable 里 - 注册观察者
    [self.stockForKVOaddObserver:selfforKeyPath:@"price"options:NSKeyValueObservingOptionNewcontext:nil];
     
    self.myLable.textColor= [UIColorredColor];
    self.myLable.text= [self.stockForKVOvalueForKey:@"price"];
     
    // 创建 button 按钮
    UIButton*button = [UIButtonbuttonWithType:UIButtonTypeRoundedRect];
    [buttonsetFrame:CGRectMake(90,150,140,42)];
    [buttonsetTitle:@"按钮"forState:UIControlStateNormal];
    [buttonaddTarget:selfaction:@selector(buttonAction)forControlEvents:UIControlEventTouchUpInside];
    [self.viewaddSubview:button];
}
 
// button响应方法
- (void)buttonAction
{
    [self.stockForKVOsetValue:@"20.0"forKey:@"price"];
}
 
// 回调方法
- (void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)objectchange:(NSDictionary*)change context:(void*)context
{
    if([keyPath isEqualToString:@"price"])
    {
        self.myLable.text= [self.stockForKVOvalueForKey:@"price"];
    }
}
 
- (void)dealloc
{
    // 移除观察者
    [self.stockForKVOremoveObserver:selfforKeyPath:@"price"];
}

0 0
原创粉丝点击