KVO

监听者监听对象发生改变 执行- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context这个方法,主要用于实时监听

#import "AppDelegate.h"
#import "Person.h"
@interface AppDelegate ()
@property (nonatomic,retain) Person *p;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    
    
    //创建一个对象
    self.p = [[Person alloc] init];
    self.p.name = @"zhangsan";
    
    //添加观察者
    [self.p addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew  | NSKeyValueObservingOptionOld context:@""];
    
    
    self.p.name = @"lisi";
    
    
    
    [self.window makeKeyAndVisible];
    return YES;
}

//观察者观察到被观察者的值发生变化,状态发生变化,或者执行了某个事件之后,执行的方法.
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    NSLog(@"keyPath = %@",keyPath);
    NSLog(@"object = %@",object);
    NSLog(@"change = %@",change);
    NSLog(@"context = %@",context);
    NSLog(@"%@",[change objectForKey:@"new"]);
}

打印结果如下:
2015-05-22 10:06:42.154 LessonKVO[2402:1257315] keyPath = name
2015-05-22 10:06:42.154 LessonKVO[2402:1257315] object = <Person: 0x7ff24954a3e0>
2015-05-22 10:06:42.156 LessonKVO[2402:1257315] change = {
kind = 1;
new = lisi;
old = zhangsan;
}
2015-05-22 10:06:42.156 LessonKVO[2402:1257315] context =
2015-05-22 10:06:42.156 LessonKVO[2402:1257315] lisi
2015-05-22 10:06:42.160 LessonKVO[2402:1257315] Application windows are expected to have a root view controller at the end of application launch
由于未完善 可参考 :http://blog.csdn.net/totogo2010/article/details/7779402,http://blog.csdn.net/wzzvictory/article/details/9674431#

 posted on 2015-05-22 11:03  ianhao_cn  阅读(150)  评论(0编辑  收藏  举报