Search code examples
iphoneiosobjective-cios6storyboard

Encapsulation when moving from xib to storyboards?


With xibs, you could call different initializers:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Fetch Note...
    // Initialize Edit Note View Controller with the fetched Note
    EditNoteViewController *vc = [[EditNoteViewController alloc] initWithNote:note];

    // Push View Controller onto Navigation Stack
    [self.navigationController pushViewController:vc animated:YES];
}

This allowed me to keep my variables (in the EditNoteViewController) private and I was also able to set default values to some of the variables, e.g.

- (id)initWithNote:(Note *)note {
    // ....
    if (self) {
        self.note = note;
        self.isEditing = YES;
    }
    return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    //...
    if (self) {
        self.isEditing = NO;
    }
    return self;
}

I'm now trying to work with storyboards:

  • is there a good way to set variables from prepareForSegue without exposing variables or any other implementation?
  • how can I set default values?

Please be as explicit as possible


Solution

  • You should user prepareForSegue. Expose only what you need to in the receiving View Controller

    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Prepare for next view controller
      if ([segue.identifier isEqualToString:@"someThing"]) {
        SomeThingViewController *viewController = segue.destinationViewController;
        viewController.someProperty = @"something else";
      }
    }
    

    The property someProperty would need to be exposed in the header for SomeThingViewController

    @property (nonatomic, strong) NSString *someProperty;
    

    To set a default value, check the value of the property in viewDidLoad of the receiving view controller

    if (someProperty==nil) someProperty = @"Default";