KVC + KVO

来源:互联网 发布:淘宝关键词价格查询 编辑:程序博客网 时间:2024/06/04 19:27

KVC

//KVC赋值对象的属性

[p1 setValue:@"" forKey:@"name"];

KVO

  • (void)viewDidLoad {
    [super viewDidLoad];

    //1.初始化对象
    _p1 = [[Person alloc] init];

    //2.添加观察者对象
    //参数1:监听的对象
    //参数2:当前对象
    //参数3:新值和旧值
    //参数4:形参内容
    [_p1 addObserver:self forKeyPath:@”name” options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:@”hello”];
    }

  • (void)changeValue
    {
    //3.通过kvc改修对象属性的值
    NSString *name = [NSString stringWithFormat:@”%d”,arc4random() % 100000];
    [_p1 setValue:name forKey:@”name”];
    }

//4.对象属性值修改时回调
- (void)observeValueForKeyPath:(NSString )keyPath ofObject:(id)object change:(NSDictionary )change context:(void *)context
{
//keyPath属性名字
if ([keyPath isEqualToString:@”name”]) {
//object被监听的对象 person的对象
Person p1 = (Person )object;
_label.text = p1.name;
}

//change新值 和 旧值//context 形参值

// NSLog(@”keyPath == %@”,keyPath);
// NSLog(@”object == %@”,object);
// NSLog(@”change == %@”,change);
// NSLog(@”context == %@”,context);
}

KVO反向传值

//VC1

  • (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    _label = [[UILabel alloc] initWithFrame:CGRectMake(100, 200, 200, 50)];
    _label.backgroundColor = [UIColor grayColor];
    _label.textColor = [UIColor redColor];
    [self.view addSubview:_label];

    //1.初始化被监听的对象
    self.second = [[SecondViewController alloc] init];

    //2.添加观察者对象
    [self.second addObserver:self forKeyPath:@”name” options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];
    }

  • (void)touchesBegan:(NSSet )touches withEvent:(UIEvent )event
    {
    [self presentViewController:self.second animated:YES completion:nil];
    }

//4.对象的属性被修改时的回调
- (void)observeValueForKeyPath:(NSString )keyPath ofObject:(SecondViewController )object change:(NSDictionary )change context:(void )context
{
if ([keyPath isEqualToString:@”name”]) {
_label.text = object.name;
}
}

//VC2

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{
//3.修改对象属性的值
[self setValue:@”KVO反向传值” forKey:@”name”];
[self dismissViewControllerAnimated:YES completion:nil];
}

0 0
原创粉丝点击