2013-12-21 54 views
-2

爲了更好地理解KVO,我創建了一個簡單的應用程序,其中包含1個按鈕和2個非常基本的模型類:Book和Author。我想在作者更改時觸發本書。例如,一個簡單的KVO例子,爲什麼不觸發觀察者?KVO使用此代碼

#import "AppDelegate.h" 
#import "Book.h" 
#import "Author.h" 

@implementation AppDelegate { 
    Book *home; 
    Author *nancy; 
} 

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification 
{ 
    // Insert code here to initialize your application 

    NSLog(@"FunWithKVO"); 

    nancy = [[Author alloc] init]; 

    [nancy setFirstName:@"Nancy"]; 
    [nancy setLastName:@"Drew"]; 

    home = [[Book alloc] init]; 

    [home addObserver:nancy forKeyPath:@"lastName" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:NULL]; 

    [home setAuthor:@"Nancy Drew"]; 

} 

- (IBAction)changeName:(id)sender { 
    NSLog(@"%@",[home author]); 

    [nancy setLastName:@"Martin"]; 
} 

@end 

現在這應該被稱爲但並不:

#import "Book.h" 

@implementation Book 

@synthesize author; 

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { 

    [author setValue:[NSString stringWithFormat:@"Nancy %@",[change value]]]; 

    [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; 

    NSLog(@"name is now: %@",author); 
} 

@end 
+0

沒有必要是粗魯;你的代碼是錯誤的,而不是框架。 –

回答

1

您混合起來的觀測和在登記的觀察對象。 nancy是由home待觀察對象,因此它應該是

[nancy addObserver:home forKeyPath:@"lastName" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:NULL]; 
+0

你知不知道你是一位有資本的天才G. – user3124055