相关疑难解决方法(0)

是否有必要覆盖bind:toObject:withKeyPath:options:在NSView子类中实现绑定?

我有一个NSView子类,它具有我想要绑定的属性.我在子类中实现了以下内容:

myView.h:

@property (readwrite, retain) NSArray *representedObjects;
Run Code Online (Sandbox Code Playgroud)

myView.m:

@synthesize representedObjects;

+(void)initialize
{
    [self exposeBinding: @"representedObjects"];
}


-(void)bind:(NSString *)binding toObject:(id)observableController withKeyPath:(NSString *)keyPath options:(NSDictionary *)options
{
    if ([binding isEqualToString:@"representedObjects"]) {
        [observableController addObserver: self forKeyPath:@"arrangedObjects" options:NSKeyValueChangeNewKey context:nil];
    } else {
        [super bind: binding toObject:observableController withKeyPath:keyPath options: options];
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"arrangedObjects"]) {
        [self setRepresentedObjects: [object arrangedObjects]];
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我创建了对arrayController的绑定-[AppController awakeFromNib]:

[myView bind:@"representedObjects" toObject:arrayController withKeyPath:@"arrangedObjects" options: nil];
Run Code Online (Sandbox Code Playgroud)

这是实现绑定的正确方法吗?它涉及很多锅炉板代码,这让我觉得我做错了.

我认为NSObject会自动实现我手动完成的工作,-bind:toObject:withKeyPath:options:但事实并非如此.如果我注释掉我-bind:toObject:withKeyPath:options: …

cocoa objective-c cocoa-bindings

6
推荐指数
1
解决办法
2130
查看次数

标签 统计

cocoa ×1

cocoa-bindings ×1

objective-c ×1