Reputation: 50826
I have a class which is responsible and the owner of building my model objects. It allocates memory for the models and has them retained and is responsible for releasing them when dealloc happens.
Now I have a respective UIViewController which is acting as the client in this case. It will have several instance variables, pointing to the model(s) it needs. It doesn't need to allocate the memory for them as the class responsible for doing so has already done it. Do I still need to release the memory from the client? Here's 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 the 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 don't mind any syntactical errors as I just wrote this on the fly here. I think my point was illustrated fine in code though.
Thank you..
Upvotes: 4
Views: 947
Reputation: 96333
Assuming that you declared ClientviewController's modelA
property as either @property(retain)
, @property(copy)
, or @property(mutableCopy)
, you are retaining the value of that property, so you must release it.
EDIT from the year 2013: Assuming you're not using ARC. ARC will do that for you, so there's usually no need to implement dealloc
at all under ARC. When not using ARC, you need to release everything you own.
Upvotes: 4
Reputation: 8114
YOu should have done it lie this
- (void)viewDidLoad
{
ModelClassA *myModelA = [instanceOfModelHolder modelA];
self.myModelA = myModelA;
[myModelA release];
}
As releasing it any where else may lead to memory leaks or sometimes even crash the application if the reference count are not cared properly.
Please also note that you have not made ModelClassA myModelA;
a property so you should avoid release it in the dealloc until you are sure that it has reference count greater than 1.
Upvotes: 0
Reputation: 46051
You should put [super dealloc];
last in your own dealloc.
- (void)dealloc
{
[modelA release];
[super dealloc];
}
As for your question about releasing in the last dealloc it depends on how you specified the @property myModelA, is it a "retain" or a "copy" property you should do a release. Is it a "copy" you are actually in charge of a new object.
Upvotes: 0