iosobjective-cconstructoruistoryboardinit

How to use custom init of ViewController in Storyboard


I have one storyboard in which all of my viewControllers are placed. I'm using StoryboardID as:

AddNewPatientViewController * viewController =[[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"addNewPatientVC"];
 [self presentViewController:viewController animated:YES completion:nil];

In AddNewPatientViewController I've added a custom init method or constructor you can say as:

-(id) initWithoutAppointment
{
    self = [super init];
    if (self) {
        self.roomBedNumberField.hidden = true;
    }
    return self;
}

So my question is by using the above wat of presenting view controller how can I init it with this custom init I've made.

I've tried doing this as areplacement of above code but it didn't work.

AddNewPatientViewController *viewController = [[AddNewPatientViewController alloc] initWithoutAppointment];
 [self presentViewController:viewController animated:YES completion:nil]; 

Solution

  • It's not the best idea to use this approach. At first, I want to suggest you to set this property after instantiation; it would be better

    If you anyway want to make such constructor, you can place your code with instantiation to it, so it will look like

    -(id) initWithoutAppointment
    {
        self = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"addNewPatientVC"];
        if (self) {
            self.roomBedNumberField.hidden = true;
        }
        return self;
    }
    

    but it won't be a good code

    EDITED

    May be it's the question of style, but I would rather prefer not to do this because view controller doesn't have to know about UIStoryboard; if you want to have such method, it would be better to move it to some separate factory. If I chose to use this VC in other projects without Storyboard, or with storyboards, but with another name, it will be error-prone.