John Anthony
John Anthony

Reputation: 547

Accessing self.view in UIViewControllers init method causes crash

I have a UIViewController with a custom init method that looks like this:

- (id)initWithFrame:(CGRect)frame_ customObject:(CustomObject *)object_ {
    if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        self = [super initWithNibName:@"ArtistViewController_iPad" bundle:nil];
    } else {
        self = [super initWithNibName:@"ArtistViewController" bundle:nil];
    }

    [self.view setFrame:frame_];

    self.customObject = object_;

    return self;
}

But when [self.view setFrame:frame_]; is called, it crashes with this in the log:

(null) libc++abi.dylib: terminate called throwing an exception

This is how I allocate the UIViewController from another UIViewController:

CGRect frame = self.view.frame;

artistViewController = [[ArtistViewController alloc] initWithFrame:frame customObject:anObject];

the frame exists. self exists from [super initWithNibName:bundle];

But self.view seems to not exist. The nib files exist and have their view outlet hooked up.

Why does this happen?

Upvotes: 1

Views: 1543

Answers (1)

Jody Hagins
Jody Hagins

Reputation: 28409

You should not access the view from within the initializer. There are several more appropriate places to do this work, depending on what you really want to accomplish.

Read the view controller lifecycle to understand where you may want to place your modifications.

http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/ViewLoadingandUnloading/ViewLoadingandUnloading.html#//apple_ref/doc/uid/TP40007457-CH10-SW1

Upvotes: 3

Related Questions