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?
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,neworcopyin there name, they will return an object that the caller is responsible torelease.)So you need to keep the
autoreleasebecause that method don’t exist after thereturnand won’t be able to call release on it.The Object that is calling
cardWithCardshouldretainthe object if it want it to be alive more that the time of that particular method.The code should look something like this
This is in the case where
myCardis declare like thisSo 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:
and you will need to something like this later on
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.