Is it necessary to override bind:toObject:withKeyPath:options: in an NSView subclass to implement binding?

佐手、 提交于 2019-11-30 04:04:07

No, you shouldn’t need that glue code.

What do you mean by “doesn’t seem to be the case”? What happens if you omit it?

No, it is not necessary to override bind:.

As Peter Hosey wrote in the comment to the earlier answer, you can call exposeBinding: and implement KVC- and KVO-compliant accessors and setters.

MyView.h:

@interface MyView : NSView {
    NSArray *_representedObjects;
}

// IBOutlet is not required for bindings, but by adding it you can ALSO use
// an outlet
@property (readonly, retain) IBOutlet NSArray *representedObjects;

@end

MyView.m:

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

// Use a custom setter, because presumably, the view needs to re-draw
- (void)setRepresentedObjects:(NSArray *)representedObjects {
    [self willChangeValueForKey:@"representedObjects"];
    // Based on automatic garbage collection
    _representedObjects = representedObjects;
    [self didChangeValueForKey:@"representedObjects"];

    [self setNeedsDisplayInRect:[self visibleRect]];
}

Then you can set the binding programmatically:

[myView bind:@"representedObjects" toObject:arrayController withKeyPath:@"arrangedObjects" options: nil];

To set the binding in Interface Builder, however, you must create a custom palette.

You definitely DO need to implement -bind:toObject:withKeyPath:options: in a custom view if you want to implement bindings in that view. Your implementation in myView.m is pretty much spot on.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!