Search code examples
iphoneobjective-cdelegationparentviewcontroller

Is it usually a bad sign that I am relying on self.parentViewController and/or self.presentingViewController in my design


I have a SubSelectVC that handles sub-selection choice that is presented modally from a SearchVC. The SubSelectVC has a -(void)didSelectRowAtIndexPath that performs these options, roughly:

if ([[[UIDevice currentDevice] systemVersion] intValue] < 5) {
    ((SearchVC *)self.parentViewController.filters.filterValue = @"Some value";
}
else {
    ((SearchVC *)self.presentingViewController.filters.filterValue = @"Some value";
}

This seems like it screams of bad design but, I mean, the option to do it this way is there and it's so easy! What's wrong with this, and how would I make it right? (Should I use delegation?)


Solution

  • Yes, I think a better encapsulated version of this would be to define a delegate protocol in the header file for SubSelectVC, and a delegate property on SubSelectVC.

    That way your view controller is reusable for any task that requires modal selection from a list.

    EDIT: added example header:

    SubSelectVC.h:

    @protocol SubSelectVCDelegate
    
    - (void)itemSelected:(NSString *)itemName;
    
    @end
    
    @interface SubSelectVC : UIViewController
    
    @property (assign) id <SubSelectVCDelegate> delegate;
    
    // etc...
    
    @end