iOS KVO的基本使用点

  1. 如果监听的是值类型的话,在打印change的时候changer对一个的kind是1,如果是集合类型或者数组,那么kind对应的是2
typedef NS_ENUM(NSUInteger, NSKeyValueChange) {
    NSKeyValueChangeSetting = 1,
    NSKeyValueChangeInsertion = 2,
    NSKeyValueChangeRemoval = 3,
    NSKeyValueChangeReplacement = 4,
};
Mark :注意:监听数组的时候,如果直接用addObject是没有作用的得用:
    [[self.person mutableArrayValueForKey:@"array"] addObject:@"1"];

2 .移除和添加观察者要一一对应否则会造成崩溃.

  1. 绑定监听关系,场景:一个属性的改变,会导致另外一个属性的改变,比如我们有个person类,她有三个属性,然而fullName是由lastName和firstName拼接成的:
@property (nonatomic,copy)NSString *fullName;
@property (nonatomic,copy)NSString *firstName;
@property (nonatomic,copy)NSString *lastName;
+(NSSet *)keyPathsForValuesAffectingFullName
{
    return [NSSet setWithObjects:@"lastName",@"firstName", nil];
}

当我们监听fullName的时候:

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

当修改firstName的值,就会走到系统的observeValueForKeyPath方法

2019-01-14 14:43:53.860862+0800 KVO_learn[33511:363993] {
kind = 1;
notificationIsPrior = 1;
old = "(null)(null)";
}
2019-01-14 14:43:53.861199+0800 KVO_learn[33511:363993] {
kind = 1;
new = "san(null)";
old = "(null)(null)";
}

  1. automaticallyNotifiesObserversOf类方法,系统默认返回YES,但是我们可以重写为NO:
+ (BOOL)automaticallyNotifiesObserversOfFullName{
    return NO;
}

此时监听的方法会失效,我们需要手动发送通知告诉系统:

    [self.person willChangeValueForKey:@"firstName"];
    self.person.firstName = @"san";
    [self.person didChangeValueForKey:@"firstName"];

需要注意的是,此时observeValueForKeyPath会收到四次通知了,如果我们options为NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld | NSKeyValueObservingOptionPrior

你可能感兴趣的:(iOS KVO的基本使用点)