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

前端 未结 3 650
星月不相逢
星月不相逢 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: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.

提交回复
热议问题