2

I'm new to storyboards and I'm having a problem with custom initialization.

Before using storyboards I used to do this to push a view controller from a table which has a custom initialization:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    //Creating Dummy Hotel
    HotelItem *hotel = [[HotelItem alloc] init];

    HotelDetailViewController *controller = [HotelDetailViewController controllerWithHotel:hotel];
    controller.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:controller animated:YES];

    [hotel release];
}

Now with storyboards I'm using prepareForSegue instead of didSelectRowAtIndexPath which turned into this:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{

    //Creating Dummy Hotel
    HotelItem *hotel = [[HotelItem alloc] init];
    hotel.name = @"Hotelucho";

    // Make sure we're referring to the correct segue
    if ([[segue identifier] isEqualToString:@"ShowSelectedHotel"]) {

        HotelDetailViewController *controller = [segue destinationViewController];

    }
}

I know that I can change my private variable "hotel" and set the property right after the [segue destinationViewController] but I find more useful to call my custom init method.

Is there a way to achieve this?

Chompas
  • 553
  • 8
  • 19

1 Answers1

2

IF you've got a big chunk of code you need to do after an init, you might want to create a separate method for it, and then call that method in initWithCoder: and initWithFrame:.

Check this answer for more info: Objective C - Custom view and implementing init method?

Community
  • 1
  • 1
Adis
  • 4,512
  • 2
  • 33
  • 40
  • But regarding the code I posted above. If I made my initialization in initWithCoder and initWithFrame, how I send the hotel variable throught that methods like I was doing in "controllerWithHotel:"? – Chompas Oct 22 '12 at 13:03
  • In your prepareForSegue:: method, just set the property on your controller object. Don't forget to refresh anything that you need to refresh after setting the property. – Adis Oct 22 '12 at 13:12
  • So I can't keep my hotel property private because I can't use a custom Init like controllerWithHotel: right? – Chompas Oct 22 '12 at 13:14
  • And also, what de you mean with refresh anything after setting the property? Thanks in advance :) – Chompas Oct 22 '12 at 13:19
  • Right, it should be a public property. As for the second question, your init method will be called before you set the property. So, for example, if you set an UILabel value, it won't reflect the changes you do while setting the property. In that case, just remove the method called in init and call it in viewDidAppear: or wherever you deem necessary. – Adis Oct 22 '12 at 13:41
  • Oh yes, I see what you mean. Thanks for your answers. – Chompas Oct 22 '12 at 13:54