ARC releasing ViewController prematurely

不打扰是莪最后的温柔 提交于 2019-12-11 05:58:58

问题


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!



来源:https://stackoverflow.com/questions/9390348/arc-releasing-viewcontroller-prematurely

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!