Static analyzer says I have the potential leak of an object

This is an object I made to do some flash cards. The first method (I left out the main part) generates a NSMutabaleArray of Card objects with the passed in operator and works fine. The second method, "drawFromDeck" gets called on a Deck object from my view controller and also works fine, but the Static Analyzer says I may be leaking an object.

Here is the code.

#import "Deck.h"

@class Deck;
@implementation Deck

@synthesize cards;

- (id)initDeckWithOperator: (NSString*)mathOper {

...

 return self;
}

- (id)drawFromDeck {
    int index = random() % [cards count];
    Card* selectedCard = [[cards objectAtIndex:index] retain];
    [cards removeObjectAtIndex:index];
    return selectedCard;
}

@end

Answers


Yes you're leaking an object. You should

return [selectedCard autorelease];

The reason being you've -retained the selectedCard, so you've got the responsibility to -release it. But you can't use -release since it must be valid after the function ends, so you need to use -autorelease to transfer the ownership to the auto-release pool.

Of course, methods calling -drawFromDeck shouldn't -release its return value.


Need Your Help

Programmatically Detecting Valid Style Properties In Flex

apache-flex flash actionscript-3 actionscript air

If I want to know if an object has a particular property I can code this:

Differentiate between different constraint violations in hibernate

java mysql database hibernate spring-jdbc

I have a database table which has both Foreign key and Unique key constraints. To make changes in the database table, i am using java application which uses hibernate. To be more precise i am doing