iOS之KVO Tips

  1. keykeypath匹配

    addObserver: forKeyPath: options: context:的“keypath”和setValue: forKey的“key”或setValue: forKeyPath:的“keyPath”或setter方法对应的属性名保持一致,observeValueForKeyPath: ofObject: change: context: 方法才会被触发。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    //self.student.name
    [self.student addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:NULL];

    [self.student setName:@"baylee"];//student有"name"属性或成员变量
    [self.student setValue:@"baylee" forKey:@"name"];

    //self.student有teacher属性,teacher有个className属性
    [self.student addObserver:self forKeyPath:@"teacher.className" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:NULL];

    self.student.teacher.className = @"english";
    [self.student setValue:@"english" forKeyPath:@"teacher.className"];
  2. keykeyPath表示属性或变量路径,一定要用@"propertyName"@"obj.propertyName"这样的路径字符串,而不是obj.propertyName这样的形式。

  3. 区别key和keyPath

    key一般是被观察对象的直接属性、成员变量等,比如上面代码中的self.studentname属性,student是被观察对象,name是student的直接属性,key直接使用@"name"

    keyPath一般是被观察对象的间接属性或成员变量,比如上面代码中,要观察self.studentteacher属性的className属性或成员变量,而被对象是self.student,需要使用keyPath为@"teacher.className"