KVC和KVO,KVC:即Key-Value-Coding而KVO:即Key-Value-Observer
- #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:NSKeyValueObservingOptio nNew|NSKeyValueObservingOptio nOld 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 dismissModalViewControll erAnimated:YES]; -
-
- }
-
- -
(IBAction)otherClicked:(id)sender { -
-
NSLog(@"firstVC name is %@",[self valueForKey:@"name"]); - }
- @end