Skip to main content

ViewController gets deallocated which leads to crash



I have a view in my storyboard which I assigned an identifier called "MainView". However if I add its view to the subview, everything that follows produces a crash (e.g. pressing a button)







MainViewController *mvc = [self.storyboard instantiateViewControllerWithIdentifier:@"MainView"];

[self.view addSubview:mvc.view];







This is the action triggered by the button : (MainViewController.h)







-(IBAction)showUsername:(id)sender{



[testLabel setText:@"username"];



}







and the crash log :







-[MainViewController performSelector:withObject:withObject:]: message sent to deallocated instance 0x44e0810







I use ARC.


Comments

  1. Best way to deal with this is using a property. Here's how:

    In your .h file:

    #import "MainViewController.h"

    @interface MyClass : UIViewController

    @property (strong, nonatomic) MainViewController *mvc;

    @end


    In your .m file:

    #import "MyClass.h"

    @implementation MyClass

    @synthesize mvc;

    // Your code here
    - (void)yourMethodHere {
    self.mvc = [self.storyboard instantiateViewControllerWithIdentifier:@"MainView"];
    [self.view addSubview:mvc.view];
    }

    ReplyDelete

Post a Comment

Popular posts from this blog

Wildcards in a hosts file

I want to setup my local development machine so that any requests for *.local are redirected to localhost . The idea is that as I develop multiple sites, I can just add vhosts to Apache called site1.local , site2.local etc, and have them all resolve to localhost , while Apache serves a different site accordingly.