ARC releasing ViewController prematurely

2019-07-25 22:27发布

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

2条回答
Anthone
2楼-- · 2019-07-25 22:57

Please use the strong key

@property (strong, nonatomic) MainViewController *mvc;
查看更多
太酷不给撩
3楼-- · 2019-07-25 22:59

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!

查看更多
登录 后发表回答