Re: NSMutableArray + NSEnumerator = No Memory
Re: NSMutableArray + NSEnumerator = No Memory
- Subject: Re: NSMutableArray + NSEnumerator = No Memory
- From: Chris Suter <email@hidden>
- Date: Sun, 23 Sep 2007 09:18:09 +1000
On 23/09/2007, at 4:36 AM, James Bucanek wrote:
1 - Use objectAtIndex: to iterate through the array.
2 - Create an auto release pool and discard the NSEnumerator during
every search.
3 - Abandon NSArray and roll my own collection.
I'm leaning towards (1) because it minimizes the code change and
shouldn't incur too much additional overhead. (2) will keep me from
running out of memory, but doesn't guarantee that other calls to
objectEnumerator won't make gratuitous copies of the array.
(3) is ultimately the best solution, as I can increase the speed
and reduce the memory footprint of the collection considerably by
dropping NSArray altogether. But that's a lot of coding and I'd
rather not make any radical changes in my application at the moment.
There is a fourth option which is that you implement your own
enumerator. Something like this would do:
@interface MemoryEfficientEnumerator : NSEnumerator {
int index;
unsigned numObjects;
NSArray *array;
}
@end
@implementation MemoryEfficientEnumerator
- (MemoryEfficientEnumerator *)initWithArray:(NSArray *)anArray
{
if (![super init])
return nil;
numObjects = [anArray count];
array = [anArray retain];
}
+ (MemoryEfficientEnumerator *)enumeratorWithArray:(NSArray *)anArray
{
return [[[MemoryEfficientEnumerator alloc]
initWithArray:anArray] autorelease];
}
- (void)dealloc
{
[array release];
[super dealloc];
}
- (id)nextObject
{
if (index >= numObjects)
return nil;
return [array objectAtIndex:index++];
}
@end
@interface NSArray (MemoryEfficientEnumerator)
- (MemoryEfficientEnumerator *)memoryEfficientEnumerator;
@end
@implementation NSArray (MemoryEfficientEnumerator)
- (MemoryEfficientEnumerator *)memoryEfficientEnumerator
{
return [MemoryEfficientEnumerator enumeratorWithArray:self];
}
@end
Attachment:
smime.p7s
Description: S/MIME cryptographic signature
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden