// KVC: Key Value Coding, 常见作用:给模型属性赋值
// KVO: Key Value Observing, 常用作用:监听模型属性值的改变
//
// ViewController.m
// 11-通知、KVO、代理
//
// Created by xiaomage on 15/6/6.
// Copyright (c) 2015年 xiaomage. All rights reserved.
// #import "ViewController.h"
#import "XMGPerson.h" @interface ViewController ()
@property (nonatomic, strong) XMGPerson *p1;
@property (nonatomic, strong) XMGPerson *p2;
@property (nonatomic, strong) XMGPerson *p3;
@end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad]; // self.p1 = [[XMGPerson alloc] init];
// self.p1.name = @"p1";
//
// self.p2 = [[XMGPerson alloc] init];
// self.p2.name = @"p2";
//
// self.p3 = [[XMGPerson alloc] init];
// self.p3.name = @"p3";
// 同一个通知TestNotification可以被多个对象person监听
// 当收到TestNotification通知就调用self.p1的test方法
// [[NSNotificationCenter defaultCenter] addObserver:self.p1 selector:@selector(test) name:@"TestNotification" object:nil];
// [[NSNotificationCenter defaultCenter] addObserver:self.p2 selector:@selector(test) name:@"TestNotification" object:nil];
// [[NSNotificationCenter defaultCenter] addObserver:self.p3 selector:@selector(test) name:@"TestNotification" object:nil];
// 多个对象可以发出同一个通知
//对象@“123”发出TestNotification通知
// [[NSNotificationCenter defaultCenter] postNotificationName:@"TestNotification" object:@"123"];
// [[NSNotificationCenter defaultCenter] postNotificationName:@"TestNotification" object:@"345"]; // KVC: Key Value Coding, 常见作用:给模型属性赋值
// KVO: Key Value Observing, 常用作用:监听模型属性值的改变 self.p1 = [[XMGPerson alloc] init];
self.p1.name = @"p1";
//self.p1 监听属性 name的改变,NSKeyValueObservingOptionOld表示监听方法中的NSDictional显示旧值
[self.p1 addObserver:self forKeyPath:@"name" options: NSKeyValueObservingOptionOld context:nil]; self.p1.name = @"pppp1";
}
//所有的通知监听 都要在dealloc销毁时removeObserver
- (void)dealloc
{
[self.p1 removeObserver:self forKeyPath:@"name"];
} #pragma mark - KVO监听方法
/**
* 当监听到object的keyPath属性发生了改变
*这个方法是NSObject的类扩展方法,用来监听对象属性改变
*keyPath属性名称如name
*id 对象 如self.p1
*change 记录改变前后的值
*/
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
NSLog(@"监听到%@对象的%@属性发生了改变, %@", object, keyPath, change);
} @end