1

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
Steve
  • 21
  • 1

1 Answers1

6

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.

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
  • I'd say it would be clearer to just not retain the card in the first place. He has no reason to take ownership at that point. Card* selectedCard = [cards objectAtIndex:index]; – Joshua Weinberg Jul 02 '10 at 15:59
  • 3
    @Joshua Weinberg - However, if he did that it may be deallocated at the instant -removeObjectAtIndex: was called. By using autorelease, at least it will exist long enough to be returned from the method. – Brad Larson Jul 02 '10 at 17:38
  • tested my assumption, I was wrong. Makes sense now that I think about it. – Joshua Weinberg Jul 03 '10 at 03:45