Andrey Chernukha
Andrey Chernukha

Reputation: 21808

How to manage memory for autorelease objects

I work on implementation of playing card class and i've created the following method:

+ (id)cardWithCard:(Card *)newCard
{
Card *card = [[[Card alloc] initWithCard:newCard] autorelease];
return card;
}

i use autorelease method here cause otherwise Product->Analyze warns me about potential leak. Everything works fine until variable myCard (which was allocated earlier) to which a new value was assigned like this:myCard = [Card cardWithCard:newCard] is sent to a different method as a parameter. It turns out to be deallocated there and my app crashes. How should i resolve this issue? Get autorelease method away despite warnings of Analyze?

Upvotes: 1

Views: 91

Answers (1)

Vincent Bernier
Vincent Bernier

Reputation: 8664

Each method or object should be responsible for retaining object that it is interested in.
It it easier to maintain. (Exception are for method that have alloc, new or copy in there name, they will return an object that the caller is responsible to release.)

So you need to keep the autorelease because that method don't exist after the return and won't be able to call release on it.
The Object that is calling cardWithCard should retain the object if it want it to be alive more that the time of that particular method.

The code should look something like this

self.myCard = [Card cardWithCard:newCard];

This is in the case where myCard is declare like this

@property (nonatomic, retain) Card * myCard;

So in this case the property will do the retain for you and will release that object when you will place a new one in this property. (If you overwrite the auto-generated accessor, you will need to manage that yourself in those method)

If for some reason you don't want to use a property... well it's your choice :-)
You will need to do something like this:

myCard = [[Card cardWithCard:newCard] retain];

and you will need to something like this later on

[myCard release];

If it's not in the same method the analyser will compline, and if it's in the same method you probably don't need the retain.

Upvotes: 2

Related Questions