【发布时间】:2011-04-16 21:12:27
【问题描述】:
我有一个视图 MyView,它有一些图像,我想将这些图像与我的 AppDelegate 中的一个数组绑定。
MyView类
@interface MyView : NSView {
@private
NSArray *images;
}
@end
+ (void)initialize
{
[self exposeBinding:@"images"];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
NSLog(@"Changed!");
}
我的AppDelegate
@property (retain) NSArray *images;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
images = [[NSMutableArray alloc] init];
[view bind:@"images" toObject:self withKeyPath:@"images" options:nil];
// [self addObserver:view forKeyPath:@"images" options:0 context:nil]; // !!!
MyImage *img = [[MyImage alloc] ...];
[self willChangeValueForKey:@"images"];
[[self images] addObject:img];
[self didChangeValueForKey:@"images"];
[img release];
}
如果没有 [self addObserver:view forKeyPath:@"images" options:0 context:nil];,则永远不会调用方法 observeValueForKeyPath:。
使用bind:时需要调用addObserver:吗? bind: 是否设置了 KVO?为什么绑定不起作用?
【问题讨论】:
标签: cocoa cocoa-bindings key-value-observing