views:

137

answers:

1

When adding objects to an NSMutableArray in a loop, what are some best practices as to reuse memory allocated for objects that are to be added to the array?

For example:

for (int i = 0; i < 5; i++)
{
    SampleObject *sampleObject = [[SampleObject alloc] init];
    sampleObject.someProperty = ...

    [sampleObjectArray addObject:sampleObject];
    [sampleObject release];
}

Is this the correct approach? I have the sampleObjectArray as a property with (nonatomic, retain) on it. Should it be copy instead of retain?

Wouldn't it be better to alloc out of the loop and then release when the loop completes?

+3  A: 

Have you profiled your code and found that this is an issue for you? If not, don't worry about micro-optimizing it.

That said, arrays maintain strong references to the objects they contain - when the call to addObject: completes, sampleObjectArray has a retain on sampleObject. So I think your given sample code is appropriate - you alloc/init the object, so you release it as appropriate, and it's held onto only by the array it lives in.

As for allocing out of the loop, I'm not sure that would work - you'd still have to alloc for each entry in the array, lest you wind up with five copies of the same object. That's best done within a loop, and if it's in a loop, why not in the same loop as the one you already have?

Tim