Anand
Anand

Reputation: 3760

Is it ok to retain and autorelease at the same time?

I have the following code:

@interface MyClass : NSObject
{
    NSMutableArray *items;
}
@end


@implementation MyClass

-(Item *)getItem
{
    if(items.count < 1)
    {
        [self buildItemsArray];
    }
    Item *item =  [[[items objectAtIndex:0]retain]autorelease];
    [items removeObjectAtIndex:0];
    return item;
}

-(void)buildItemsArray
{
    // ...
    [items addItem:someNewItem];
    [items addItem:someOtherNewItem];
}
@end

I have a function that returns an item. If the items go down to 0, then the items array is built again inside buildItemsArray. My game logic requires that when I return an item, I need to remove it from the array. So, I am using a retain to ensure that the item is valid till the return line (since the only other known retain happened when the item was added to the items array), and an autorelease to ensure it gets cleaned up later. I have checked that this code neither crashes nor leaks. I wonder if:

a) This is OK - the reason I ask is that I have predominantly seen code with alloc/init/autorelease, and haven't run into this case with retain/autorelease b) Is there some reason to alloc/init/autorelease instead:

Item *item =  [[Item alloc]initWithItem:[items objectAtIndex:0]autorelease];

Thanks

Upvotes: 0

Views: 128

Answers (1)

CodeSmile
CodeSmile

Reputation: 64477

This is generally ok:

Item *item = [[[items objectAtIndex:0] retain] autorelease];
[items removeObjectAtIndex:0];
return item;

Though this would make the intent clearer (returning an autoreleased object):

Item *item = [[items objectAtIndex:0] retain];
[items removeObject:item];
return [item autorelease];

No reason to alloc/init. That just adds unnecessary overhead.

Like I said in my comment, if this is a (relatively) new project, you really really really should be using ARC and not worry about these things anymore.

Upvotes: 2

Related Questions