Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get EXC_BAD_ACCESS error after adding a viewcontroller'view as subView to another viewcontroller's view?

In my application I have two view controllers.First Viewcontroller is the rootViewController of the application window. when The Button in First ViewController is clicked I add the view of the second Viewcontroller as subView to the first one's view, there is a Button in the second ViewController's view ,My problem is that the application get crashed when I tap that Button

-(void)theCheckoutViewisExpandedwitPatient:(id)patient
{
    SecondViewController *sample=[[SecondViewController alloc]init];
    CGRect rect=sample.view.frame;
    rect.origin.y=30;
    rect.origin.x=305;
    [sample.view setFrame:rect];
    [self.view addSubview:[sample view]];
}
like image 989
vignesh kumar Avatar asked May 17 '13 13:05

vignesh kumar


1 Answers

The issue is that SecondViewController is not assigned to strong variable / property, therefore it is deallocated when the method returns.

Any variable pointing to an object, inside a method (called automatic variable if I remember correctly), will be removed from the memory when the method returns. As a result, object pointed to by that variable will be released. If this object is not retained anywhere else, by for example assigning to a strong property or strong instance variable, it will be deallocated. Now, what you are doing is, you grab second view controller's view and stick it into view hierarchy of the view controller's view where this method is defined. The method returns, variable is popped off the stack, SampleViewController is not retained in any way, so it gets released. Any actions that "new" view performs, that result in a call to its view controller (the second view controller), such as button tap event notification, will end up in a crash, as that view controller is no longer in the memory.

Btw. You are simply not doing it right. Look at View Controller Containment API, if you wanna write custom containers.

like image 111
foFox Avatar answered Sep 21 '22 12:09

foFox