【发布时间】:2013-12-21 00:25:49
【问题描述】:
为了更好地理解 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
【问题讨论】:
-
没有必要粗鲁;你的代码错了,不是框架。
标签: objective-c cocoa key-value-observing