线程安全并提供在观测者恢复时额外的保护Thread-safety with special guards against observer resurrection – rdar://15985376.
更多关于 KVO 的信息,可浏览 Apple 的文档:Introduction to Key-Value Observing
#import "ViewController.h"@interfaceViewController()@end@implementationViewController-(void)viewDidLoad{[superviewDidLoad];self.timer=[[CurrentTimeralloc]init];[self.timeraddObserver:selfforKeyPath:@"date"options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOldcontext:nil];}-(void)observeValueForKeyPath:(NSString*)keyPathofObject:(id)objectchange:(NSDictionary*)changecontext:(void*)context{if([keyPathisEqualToString:@"date"]){NSLog(@"%@",change[NSKeyValueChangeNewKey]);NSString*dateStr=[NSStringstringWithFormat:@"%@",change[NSKeyValueChangeNewKey]];self.showDate.text=dateStr;}}-(void)didReceiveMemoryWarning{[superdidReceiveMemoryWarning];// Dispose of any resources that can be recreated.}@end
#import "ViewController.h"#import <FBKVOController.h>@interfaceViewController(){FBKVOController*kvoController;}@end@implementationViewController-(void)viewDidLoad{[superviewDidLoad];kvoController=[FBKVOControllercontrollerWithObserver:self];self.timer=[[CurrentTimeralloc]init];[kvoControllerobserve:self.timerkeyPath:@"date"options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNewblock:^(ViewController*view,CurrentTimer*timer,NSDictionary*change){NSString*dateStr=[NSStringstringWithFormat:@"%@",change[NSKeyValueChangeNewKey]];self.showDate.text=dateStr;}];}-(void)didReceiveMemoryWarning{[superdidReceiveMemoryWarning];// Dispose of any resources that can be recreated.}@end