Antonio MG
Antonio MG

Reputation: 20410

Objective c - Correct way to release an UIVIewController

I'm having problems releasing UIView controller, this is my code. When I press a button, I put a View on the screen in front of everything:

   viewT = [[PersonalViewController alloc] initWithNibName:@"PersonalViewController" bundle:[NSBundle mainBundle]];
//In this moment the retainCount is 1
[[AppDelegate appDelegate].window  insertSubview:viewT.view aboveSubview:[AppDelegate appDelegate].dockController.view];
[viewT release];
//Now the retain count is 3!

//... After some code, when the user press another button, I want to release the view
 [viewT.view removeFromSuperview];
//After this line, the object stills there, with a retain of 2.

So something it's happening and I don't understand. I've been reading guides about memory and I've never had this doubt before, what am I doing wrong? How can I completely release viewT???

Upvotes: 1

Views: 764

Answers (2)

beryllium
beryllium

Reputation: 29767

  • You own any object you create when

You create an object using a method whose name begins with “alloc”, “new”, “copy”, or “mutableCopy” (for example, alloc, newObject, or mutableCopy).

  • When you no longer need it, you must relinquish ownership of an object you own

You relinquish ownership of an object by sending it a release message or an autorelease message. In Cocoa terminology, relinquishing ownership of an object is therefore typically referred to as “releasing” an object.

  • You must not relinquish ownership of an object you do not own

This is just corollary of the previous policy rules, stated explicitly.

Memory Management Programming Guide

So, you need only one line of code

[viewT release];

Upvotes: 4

rob mayoff
rob mayoff

Reputation: 386008

You probably have a retain cycle. Do any of the objects in your nib have an outlet connected to File's Owner? Is that outlet declared retain? (Or strong if you're using ARC, which you're not.) Change the outlet to assign (or weak if using ARC).

Upvotes: 1

Related Questions