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

前端 未结 3 641
星月不相逢
星月不相逢 2020-12-29 00:12

I have an NSView subclass which has property which I want to be bindable. I\'ve implemented the following in the subclass:

myView.h:

@property (readwri         


        
相关标签:
3条回答
  • 2020-12-29 00:27

    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?

    0 讨论(0)
  • 2020-12-29 00:31

    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.

    0 讨论(0)
  • 2020-12-29 00:36

    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.

    0 讨论(0)
提交回复
热议问题