KVO致力于此代码

时间:2013-12-21 00:25:50

标签: objective-c cocoa key-value-observing

为了更好地理解KVO,我创建了一个带有1个按钮和2个非常基本的模型类的简单应用程序:Book和Author。我想在作者改变时触发本书。例如,一个简单的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

1 个答案:

答案 0 :(得分:1)

您在注册中混淆了观察对象和观察对象。 nancyhome要观察的对象,因此它应该是

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