ARC releasing ViewController prematurely

2019-07-25 22:40发布

问题:

I am new to ARC and I have been playing with it for less than a week. What I am trying to do is very basic. I have a view controller that displays a button. When I click the button, the corresponding selector needs to be called. However, with ARC, the application crashed with an EXC_BAD_ACCESS message. Below is the code from my MainViewController

- (void)loadView
{
    [super loadView];
    UIButton *testButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [testButton setFrame:CGRectMake(80,50,160,50)];
    [testButton setTitle:@"Click Me" forState:UIControlStateNormal];
    [testButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:testButton];
}

-(void)buttonClicked:(id)sender
{
    NSLog(@"Button Clicked");
}

I enabled Zombie Objects and was able to find the following message in the debug logs

2012-02-21 22:46:00.911 test[2601:f803] *** -[MainViewController performSelector:withObject:withObject:]: message sent to deallocated instance 0x6b4bba0

Looking at the above message, it seems to me that ARC is prematurely releasing my MainViewController. I am not sure what I am doing wrong here. Please let me know if I am missing something.

Thanks in advance

回答1:

Please use the strong key

@property (strong, nonatomic) MainViewController *mvc;


回答2:

In case anyone else has a similar symptoms to this, but is using Storyboards and Segues as in my instance - this answer helped me:

IOS 5 message sent to deallocated instance on alloc command

The fix was to set the delegate of my MKMapView to nil, during viewWillDisappear. Took ages to find that solution!