Reusing objects in loop when adding to an NSMutableArray
When adding objects to an NSMutableArray
in a loop, what are some best practices as t开发者_如何转开发o 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?
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 alloc
ing 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?
精彩评论