Question

I need some help with releasing a controller in xcode ..im not using ARC ..take a look at this simple code from my main delegate controller:

LoginViewController *login = [[LoginViewController alloc] init];
[window addSubview:login.view];
[window makeKeyAndVisible];
[login release];  // code runs if i comment out this line

If i comment out the last line the program runs. The program crashes on the last line ...i put in a zombie and here is the result: 2012-08-17 09:43:02.193 dialer[238:707] * -[LoginViewController performSelector:withObject:withObject:]: message sent to deallocated instance 0x186360

how can i trace this and why is this even happing since im allocating and releasing right away. Does it have something to do with retain , etc

Was it helpful?

Solution

The login controller is added as a subview and then released, but the addSubview method doesn't retain the controller (only the controller.view), so it can't be used any further.

You have to release it or you will have a leak, the solution is creating a property/ivar in your class and assigning the view controller to it (instead of a local variable), then release it in dealloc.

I think the point you are missing is that the [login release] statement effectively reduces the retain count of your loginViewController to zero, and the object is lost/cleaned up, which is not what you want because you still need it as long as your subview is displayed.

So your parent object (main controller, if I understand your example correctly) creates the loginController, adds the loginView as a subview (this is retained by doing the addSubview call), and then releases the controller, but you still need it to handle the login view! So the solution is to keep a reference in the main controller in order to retain it as long as needed (until you remove the loginView, or the main controller gets deallocated)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top