一看就懂demo下载,地址:github
iOS开发,肯定免不了要接触苹果的黑魔法:kvo,翻译过来有点拗口叫键值观察,如果是我翻译的话会选择叫“望咩望”,哈哈。其实kvo本质来说就是针对一个对象的变动进行操作,注意,是针对变动。如果app中有需求是针对某对象变动需要进行对应的操作的话,kvo是理想的实现技术。下面,来实践一下。
1.创建一个类,重写- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void *)context方法:
@implementation AppStatusWatcher
- (void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context {
NSLog(@"Property '%@' of object '%@' changed: %@ context: %@",keyPath,object,change,context);
}
@end
2.在app delegate中处理,定义了一个appStatus属性,当变动时,观察者watcher就会接收到通知,并且变动前后的值都可以选择传递过来:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.watcher = [AppStatusWatcher new];
[self addObserver:self.watcher forKeyPath:@"appStatus" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:@"望咩望"];
self.appStatus = @"launch";
return YES;
}
3.在app的不同阶段,改变appStatus的值:
- (void)applicationWillResignActive:(UIApplication *)application {
self.appStatus = @"inactive";
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
self.appStatus = @"background";
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
self.appStatus = @"inactive";
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
self.appStatus = @"active";
}
- (void)applicationWillTerminate:(UIApplication *)application {
self.appStatus = @"terminate";
}
4.appstatus的值一改变,watcher就会接收到通知,执行自定义操作,实际运行效果:
2016-03-21 17:59:23.663 KVO[5767:13407361] Property 'appStatus' of object '' changed: { kind = 1; new = launch; old = "";} context: 望咩望
2016-03-21 17:59:23.668 KVO[5767:13407361] Property 'appStatus' of object '' changed: { kind = 1; new = active; old = launch;} context: 望咩望
2016-03-21 17:59:28.249 KVO[5767:13407361] Property 'appStatus' of object '' changed: { kind = 1; new = inactive; old = active;} context: 望咩望
2016-03-21 17:59:28.881 KVO[5767:13407361] Property 'appStatus' of object '' changed: { kind = 1; new = background; old = inactive;} context: 望咩望
网友评论