ios通知-kvo

   // KVC: Key Value Coding, 常见作用:给模型属性赋值
    // KVO: Key Value Observing, 常用作用:监听模型属性值的改变

 

 1 //
 2 //  ViewController.m
 3 //  11-通知、KVO、代理
 4 //
 5 //  Created by xiaomage on 15/6/6.
 6 //  Copyright (c) 2015年 xiaomage. All rights reserved.
 7 //
 8 
 9 #import "ViewController.h"
10 #import "XMGPerson.h"
11 
12 @interface ViewController ()
13 @property (nonatomic, strong) XMGPerson *p1;
14 @property (nonatomic, strong) XMGPerson *p2;
15 @property (nonatomic, strong) XMGPerson *p3;
16 @end
17 
18 @implementation ViewController
19 
20 - (void)viewDidLoad {
21     [super viewDidLoad];
22     
23 //    self.p1 = [[XMGPerson alloc] init];
24 //    self.p1.name = @"p1";
25 //    
26 //    self.p2 = [[XMGPerson alloc] init];
27 //    self.p2.name = @"p2";
28 //    
29 //    self.p3 = [[XMGPerson alloc] init];
30 //    self.p3.name = @"p3";
31 //    同一个通知TestNotification可以被多个对象person监听
32 // 当收到TestNotification通知就调用self.p1的test方法
33 //    [[NSNotificationCenter defaultCenter] addObserver:self.p1 selector:@selector(test) name:@"TestNotification" object:nil];
34 //    [[NSNotificationCenter defaultCenter] addObserver:self.p2 selector:@selector(test) name:@"TestNotification" object:nil];
35 //    [[NSNotificationCenter defaultCenter] addObserver:self.p3 selector:@selector(test) name:@"TestNotification" object:nil];
36 //    多个对象可以发出同一个通知
37 //对象@“123”发出TestNotification通知
38 //    [[NSNotificationCenter defaultCenter] postNotificationName:@"TestNotification" object:@"123"];
39 //    [[NSNotificationCenter defaultCenter] postNotificationName:@"TestNotification" object:@"345"];
40     
41     // KVC: Key Value Coding, 常见作用:给模型属性赋值
42     // KVO: Key Value Observing, 常用作用:监听模型属性值的改变
43     
44     
45     self.p1 = [[XMGPerson alloc] init];
46     self.p1.name = @"p1";
47     //self.p1 监听属性 name的改变,NSKeyValueObservingOptionOld表示监听方法中的NSDictional显示旧值
48     [self.p1 addObserver:self forKeyPath:@"name" options: NSKeyValueObservingOptionOld context:nil];
49     
50     self.p1.name = @"pppp1";
51 }
52 //所有的通知监听 都要在dealloc销毁时removeObserver
53 - (void)dealloc
54 {
55     [self.p1 removeObserver:self forKeyPath:@"name"];
56 }
57 
58 #pragma mark - KVO监听方法
59 /**
60  * 当监听到object的keyPath属性发生了改变
61 *这个方法是NSObject的类扩展方法,用来监听对象属性改变
62 *keyPath属性名称如name
63 *id 对象 如self.p1
64 *change 记录改变前后的值
65  */
66 - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
67 {
68     NSLog(@"监听到%@对象的%@属性发生了改变, %@", object, keyPath, change);
69 }
70 
71 @end
View Code

 

posted @ 2016-07-13 12:51  lwx64397  阅读(338)  评论(0编辑  收藏  举报