Skip to content

Instantly share code, notes, and snippets.

@drewmccormack
Created March 28, 2013 11:03
Show Gist options
  • Save drewmccormack/5262375 to your computer and use it in GitHub Desktop.
Save drewmccormack/5262375 to your computer and use it in GitHub Desktop.
A category method for NSArray that facilitates enumeration with regular draining of the autorelease pool. Useful for those long, memory accumulating loops.
@implementation NSArray (AutoreleasePoolDraining)
-(void)enumerateObjectsDrainingEveryIterations:(NSUInteger)iterationsBetweenDrains usingBlock:(void (^)(id object, NSUInteger index, BOOL *stop))block
{
NSUInteger total = 0;
NSUInteger count = self.count;
NSUInteger numberOfChunks = (count / MAX(1,iterationsBetweenDrains) + 1);
BOOL stop = NO;
for ( NSUInteger chunk = 0; chunk < numberOfChunks; chunk++ ) {
@autoreleasepool {
for ( NSUInteger i = chunk*iterationsBetweenDrains; i < MIN(count, (chunk+1)*iterationsBetweenDrains); i++ ) {
id object = self[i];
block(object, total, &stop);
if ( stop ) break;
total++;
}
}
if ( stop ) break;
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment