Search code examples
xcodeios6uiviewcontrollerinterface-builderxib

access property of file's owner from child object


I am wondering how to access a property that lives in my File's Owner class from another class object that lives within the xib.

File's Owner of my xib is a ViewController with a property x.

UIView is in the xib file and is a subclass called CustomUIView.

How do I access property x that lives in the view controller from within CustomUIView class?

I do not want to create a new instance of the File's Owner object (or do I?), I feel like that would just make a new instance of it and not use the instantiated instance (the parent or CustomUIVIew?).

Am I just that confused overall and need to revisit some basic principals of iOS development? (I'm new to the game)


Solution

  • Add a property to your view that points to the view controller.

    @interface CustomUIView
    ...
    @property (nonatomic, weak) IBOutlet ViewController *viewController;
    ...
    @end
    

    Connect this outlet to the view controller in Interface Builder.

    Now you can access it from your view:

    self.viewController.x
    

    However, this is quite a "backward" design and I think there is probably a better way to achieve what you want. Usually the view shouldn't have direct access to the data (or even the controller). Instead it should have a set of properties that are enough to represent or render whatever the view is responsible for.

    In your case you could add the property x to your view. Any time your model (the x of your view controller) changes, you update the view. If you need to be notified about changes in your view, you can overwrite the setter in your view.

    @interface CustomUIView
    @property (nonatomic, strong) NSObject *x;
    ...
    @end
    
    @implementation CustomUIView
    - (void)setX:(NSObject *)x {
        if (_x != x) {
            _x = x;
            // x was changed, do anything you need to update the view here
            // like calling [self setNeedsDisplay] to redraw the view.
        }
    }
    ...
    @end