KVO 键值观察者

KVO(键值观察者)

//监听的创建

-(id)initChildren:(Person *)person

{

    self = [super init];

    if (self != nil) {

        //拥有所有权,防止被自动释放

       // _person = [person retain];

        self.person = _person;

        

        [_person addObserver:self forKeyPath:@"happyVal" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:@"xxx"];

        

        

    }

    return self;

    

}

//移除监听器

-(void)dealloc

{

    [_person removeObserver:self forKeyPath:@"happyVal"];

    [_person release];

 

    [super dealloc];

}

//监听变化,显示变化

- (void)observeValueForKeyPath:(NSString *)keyPath

                      ofObject:(id)object

                        change:(NSDictionary *)change

                       context:(void *)context

{

    NSLog(@"change :%@",change);

}

//监听要改变的对象 ,  self.改变的对象名  或则是 kvc(注意点这两边的key记得要一致) 定义 不能使用 _对象名直接改变对象值,这这样KVO是没有办法监听它变化的

 

 

//通知

//发出通知

[NSNotificationCenter defaultCenter]postNotificationName:定义的通知名 object:要发送的对象

 

//接收通知

[NSNotificationCenter  defaultCenter]addObserver:self selector:@selector:(action:) name:这是定义的通知方式名 object:nil];

-(void) action:(NSNotification *)notification{

}

原文地址:https://www.cnblogs.com/meixian/p/5370952.html