get “EXC_BAD_ACCESS” when trying dismissModalView

2019-08-16 00:45发布

I have a view controller named "MainView", it will call

[self presentModalViewController:playView animated:NO];

to insert a "PlayView" view controller.

When app is running at PlayView, if receiving an applicationDidReceiveMemoryWarning message, it will call MainView's viewDidUnload function and release the MainView object. In this moment, the PlayView is still alive. Every thing is fine until user click a button to leaving the PlayView, it(PlayView) will call:

[self dismissModalViewControllerAnimated:NO];

Then the application is crashed with receiving 'EXC_BAD_ACCESS' error message... I think the reason is that MainView object is gone, when PlayView want to dismiss itself, it can't find a suitable ViewController to present.

How to fix this problem? T_T

PS. the PlayView view controller is created by IB, and it is set as a retain property in MainView.

2条回答
孤傲高冷的网名
2楼-- · 2019-08-16 01:29

I suppose the problem is with your MainView. It has some outlets or properties that point to views (that lay on the main view). After memory warning MainView.view is unloaded (so it releases its subviews) and if you haven't retained them & haven't set them to nil, they are now pointing to notexisting objects. So you should set them all to nil in viewDidUnload method.

查看更多
乱世女痞
3楼-- · 2019-08-16 01:29

I seems find the problem. I have a view controller named "VCGameRule", under the MainView. And it has a declaration in the VCGameRule.h file as follow:

@property (nonatomic, retain) IBOutlet UILabel *lblInitialCash;

In VCGameRule.m, there is a code as following in a initialization function:

lblInitialCash = [[UILabel alloc] initWithFrame:CGRectMake(135, 12, 50, 20)];

And its viewDidUnload function is like this:

- (void)viewDidUnload {
   [super viewDidUnload];
   // Release any retained subviews of the main view.
   self.lblInitialCash = nil; 
}

See the problem? I try to assign an new allocated UILabel object to lblInitialCash which is a retained IBOutlet property. And I try to release the property in viewDidUnload function, then some bad thing happens....

I am still not sure what the exactly error it occurs. But I think should be the property's original allocated memory become chaos. So I receive a "EXC_BAD_ACCESS" error message when the App try to call didReceiveMemoryWarning in every loaded view controllers.

After I modify the IBOutlet property to a normal class variables, the error seems not happen again! And everything is fine now, even my App really uses a lot of memory and do many times of viewDidUnload function, App is still alive. \(^o^)/

查看更多
登录 后发表回答