Skip to content

omich @ dev, english, iPad, iPhone, sdk

Have you ever looked at the memory footprint for a long running loop in Instruments? Even though you may use a NSAutoreleasePool, the memory footprint constantly increases. I had to tweak my pool.

Say you want to sync data from your server to your iPhone or iPad APP. No matter what protocol you are using, you probably end up with a loop fetching data from your server and storing it locally. As mentionned, you’ll create a fetch thread:

  1. - (IBAction) syncStart {
  2.   [NSThread detachNewThreadSelector:@selector(syncCore:) toTarget:self withObject:nil];
  3. }

in which you iterate over a list of objects, fetch them, give feedback to the user, creating helper objects you put on auto-release. But your APP might end up eating more and more memory within that loop although you’re creating a sub-autoreleasepool you are releasing at the end of each loop:

  1. - (void) syncCore: (id) dummyArg {
  2.   NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  3.   NSEnumerator *enumerator = [listToOperateOn objectEnumerator];
  4.   [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
  5.   while ((entry = [enumerator nextObject])) {
  6.     NSAutoreleasePool *subPool = [[NSAutoreleasePool alloc] init];
  7.     // do your stuff
  8.     [subPool release];
  9.   }
  10.   [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
  11.   [self performSelectorOnMainThread:@selector(syncFinished:) withObject:@"" waitUntilDone:NO];
  12.   [pool release];
  13. }

Once you trace this code in Instruments, you see a climbing memory graph! Contrary to some examples, the Apple Docs prefer drain instead of release if you wish to release all collected objects!

  1.   [subPool drain]; // <-
  2.   [subPool release];
  3.   …
  4.   [pool drain]; // <-
  5.   [pool release];

A nice almost flat memory graph will appear in Instruments.

  • Add to favorites
  • email
  • Twitter
  • Google Bookmarks
  • Facebook
  • Digg
  • del.icio.us

Comment Feed

No Responses (yet)



Some HTML is OK

or, reply to this post via trackback.