Boaz
Boaz

Reputation: 5084

Objective C UIViewController property with a default value

I have a UIViewController (iOS) with a bool property set from the view that created it.

Can I have a default value for a property?

If I put it in ViewDidLoad it will get called even if I set the value to something different before pushing the ViewController

Some code to @Erakk's request to figure out the problem:

@implementation CreateMomentViewController

- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle
{
    // NOT GETTING EXECUTED
    CreateMomentViewController *me = [super initWithNibName:nibName bundle:nibBundle];
    me.exitButton = YES;
    return me;
}
- (void)viewDidLoad {
    [super viewDidLoad];

//    self.exitButton = YES;
    // Do any additional setup after loading the view.
}

The caller:

ChefSelectionViewController is a sub-class of CreateMomentViewController

ChefSelectionViewController *nextScreen = [self.storyboard instantiateViewControllerWithIdentifier:@"ChefSelect"];
dispatch_async(dispatch_get_main_queue(), ^{
    [self.navigationController pushViewController:nextScreen animated:YES];
});

Upvotes: 1

Views: 1742

Answers (3)

Erakk
Erakk

Reputation: 922

Try changing your initWithNibName to this:

- (id)initWithCoder:(NSCoder *)decoder
{
    self = [super initWithCoder:decoder];
    if (self) {
        self.exitButton = YES;
    }
    return self;
}

Also, i dont think you would need a subclass of a viewController just to create it, but i don't know how your flow works so it's just a comment =)

By the way, the view you are instantiating by the name of @"ChefSelect", it's class (in the xib / interface builder) should be the same as CreateMomentViewController. It could happen that you are actually instantiating ChefSelectionViewController and your code on CreateMomentsViewController would never be called.

Upvotes: 3

egarlock
egarlock

Reputation: 579

I follow this standard for setting default values.

- (void)customInit {
    // Default Values
    self.exitButton = NO;
}
- (id)init {
    if (self = [super init]) {
        [self customInit];
    }
    return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [self customInit];
    }
    return self;
}
...
...

Upvotes: 3

Luke
Luke

Reputation: 7210

I would override -initWithNibName:bundle: and put it in there. Default values belong in initializers. Make sure you call [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil].

Upvotes: 1

Related Questions