KVO

-(void)control

{

    self.person = [[Person alloc]init];

    self.person.book = [[Book alloc]init];

    

    [self.person setValue:@"lili" forKey:@"name"];

    [self.person setValue:@"20" forKey:@"age"];

    [self.person setValue:@"200" forKey:@"height"];

    

    [self.person setValue:@"ios" forKeyPath:@"book.bookName"];

    [self.person setValue:@"11.5" forKeyPath:@"book.price"];

    

    //註冊觀察者

    [self.person addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];

    

    self.label = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 100, 30)];

    

    [self.label setText:[self.person valueForKey:@"name"]];

    

    [self.view addSubview: self.label];

    

    self.button = [UIButton buttonWithType:UIButtonTypeCustom];

    

    [self.button setTitle:@"點擊" forState:UIControlStateNormal];

    [self.button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

    

    [self.button addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];

    

    [self.button setFrame:CGRectMake(100, 200, 100, 30)];

    

    [self.view addSubview:self.button];

}


-(void)click

{

    [self.person setValue:@"aa" forKey:@"name"];

}


-(void)dealloc

{

    //移除觀察者

    [self.person removeObserver:self forKeyPath:@"name"];

}


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

{

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

        [self.label setText:[self.person valueForKey:@"name"]];

    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章