iphoneobjective-ciosuibuttonloadview

iPhone App crashing in loadView method when creating a UIButton


Why does the following crash my app whenever this view is loaded?

-(void)loadView {
    UIButton *chooseSubjectButton = [[UIButton buttonWithType:UIButtonTypeDetailDisclosure] retain];
    [chooseSubjectButton addTarget:self action:@selector(chooseSubject) forControlEvents:UIControlEventTouchUpInside ];
    chooseSubjectButton.frame = CGRectMake(15.0f, 205.0f, 296.0f, 51.0f);
    [self.view addSubview:chooseSubjectButton];
}

Any help would be greatly appreciated.

Thanks!


Solution

  • My guess is, your app is not crashing actually. It just keeps calling the loadView method repeatedly because you've missed to load the view. Call [super loadView] or create a view and assign it as self.view before you add anything to self.view. The convenient way would be to use [super loadView].

    - (void)loadView {
    
        [super loadView];
        // Your Code Here
    }
    

    EDIT: This answer looks to be wrong. Please consider visiting Is it ok to call [super loadView]? as @Denis Vert pointed out in the comments.