Release this instance variable on iPhone?

I have a class that is responsible and the owner of the objects of my model. He allocates memory for models and saves them and is responsible for their release when dealloc occurs.

Now I have a corresponding UIViewController that acts as a client in this case. It will have several instance variables, indicating the model (s) it needs. He does not need to allocate memory for them, since the class responsible for this has already done so. Do I still need to free memory from the client? Here is an example

ModelHolder.m will have something like

- (NSArray *)modelA { if (modelA == nil) { modelA = [[ModelClassA alloc] init]; } return modelA } - (void)dealloc { [super dealloc]; [modelA release]; } 

Now ClientViewController will have something similar:

  @class myModelA; @interface ClientViewController : UIViewController { ModelClassA myModelA; } // more code @end #import "ModelHolder.h" @implementation ClientViewcontroller ...... etc - (void)viewDidLoad { self.myModelA = [instanceOfModelHolder modelA]; } - (void)dealloc { // am I responsible to release here? } 

Please ignore the syntax errors as I just wrote this on the fly here. I think my point was illustrated in the code.

Thanks..

+4
source share
3 answers

Assuming you have declared the ClientviewController modelA property as @property(retain) , @property(copy) or @property(mutableCopy) , you save the value of this property, so you must free it.

EDIT since 2013: suppose you are not using ARC. ARC will do this for you, so there is usually no need to implement dealloc in general under ARC. If you are not using ARC, you need to free everything that you have.

+4
source

You have to put [super dealloc]; last in your own dealloc.

 - (void)dealloc { [modelA release]; [super dealloc]; } 

As for your release question in the latest dealloc, it depends on how you specified @property myModelA, this is the save or copy property that you have to do. This is the “copy” on which you are actually responsible for the new object.

0
source

You should have done it

  - (void)viewDidLoad { ModelClassA *myModelA = [instanceOfModelHolder modelA]; self.myModelA = myModelA; [myModelA release]; } 

Like getting rid of it, somewhere else it can lead to a memory leak or sometimes even a crash of the application if the link count does not take care properly.

Also note that you did not create the ModelClassA myModelA; property ModelClassA myModelA; so you should avoid releasing it in dealloc until you make sure it has a reference count greater than 1.

0
source

All Articles