KVC和KVO,KVC:即Key-Value-Coding而KVO:即Key-Value-Observer
KVC是針對NSObject的子類,因爲它的實現是由於其括展類NSObject(NSKeyValueCoding),實現了
-(void)setValue:(id)valueforKey:(NSString *)key;
- (id)valueForKey:(NSString *)key;這兩個方法的原因。
上面的兩個方法不光針對屬性,對於類中的對象型變量同樣適用。
而KVO也差不多,它是由於NSObject(NSKeyValueObserverRegistration)和NSObject(NSKeyValueObserving)的原因,用它可以實現回調功能下面是我寫的,下面的例子將其融合在一起
- #import "BIDViewController.h"
- #import "FirstViewController.h"
- @interface BIDViewController ()
- {
- FirstViewController* first;
- }
- @end
- @implementation BIDViewController
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- // Do any additional setup after loading the view, typically from a nib.
- first=[[FirstViewController alloc] init];
- //觀察FirstViewController中的變量name
- [first addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
- }
- - (void)didReceiveMemoryWarning
- {
- [super didReceiveMemoryWarning];
- // Dispose of any resources that can be recreated.
- }
- - (IBAction)clicked:(UIButton *)sender {
- [self presentViewController:first animated:YES completion:^{}];
- }
- //如果FirstViewController中的變量name的值變化執行下面
- -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
- {
- if([keyPath isEqualToString:@"name"])
- {
- NSLog(@"observer name is %@",[first valueForKey:@"name"]);
- }
- }
- -(void)dealloc
- {
- [self removeObserver:first forKeyPath:@"name"];
- [first release];
- [super dealloc];
- }
- @end
- #import
- @interface FirstViewController : UIViewController
- {
- NSString* name;
- }
- - (IBAction)clicked:(id)sender;
- - (IBAction)otherClicked:(id)sender;
- @end
- #import "FirstViewController.h"
- @interface FirstViewController ()
- {
- }
- @end
- @implementation FirstViewController
- - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
- {
- self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
- if (self) {
- // Custom initialization
- }
- return self;
- }
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- // Do any additional setup after loading the view from its nib.
- }
- - (void)didReceiveMemoryWarning
- {
- [super didReceiveMemoryWarning];
- // Dispose of any resources that can be recreated.
- }
- - (IBAction)clicked:(id)sender {
- //當爲name設值時會執行BIDViewController中的觀察方法,就可進行回調了,不過其範圍是比不上真正意義上的回調
- [self setValue:@"chenliang" forKey:@"name"];
- // [self dismissModalViewControllerAnimated:YES];
- }
- - (IBAction)otherClicked:(id)sender {
- NSLog(@"firstVC name is %@",[self valueForKey:@"name"]);
- }
- @end