IPhone: Crash on Low Memory

I am hunting again for memory leaks and other insane bugs in my code. :)

I have a cache of frequently used files (images, data records, etc. with a TTL of about one week, and a size limited cache (100MB)). There are sometimes over 15,000 files in a directory. When the application exits, the cache writes the control file with the current cache size along with other useful information. If applications for any reason (sh .. happens sometimes) I have in this case, in order to calculate the size of all files in the application, start monitoring the size of the cache. My application crashes at this point due to low memory and I don't know why.

The memory leak detector does not detect leaks at all. I don't see either. What's wrong with the code below? Is there another quick way to calculate the total size of all files in a folder on iPhone? Maybe without listing all the contents of the directory? The code is executed on the main thread.

NSUInteger result = 0;
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSDirectoryEnumerator *dirEnum = [[[NSFileManager defaultManager] enumeratorAtPath:path] retain];
int i = 0;
while ([dirEnum nextObject]) {
   NSDictionary *attributes = [dirEnum fileAttributes];
   NSNumber* fileSize = [attributes objectForKey:NSFileSize];
   result += [fileSize unsignedIntValue];

   if (++i % 500 == 0) { // I tried lower values too   
      [pool drain];
   }
}
[dirEnum release];
dirEnum = nil;
[pool release];
pool = nil;

      

Thanks, MacTouch

+2


a source to share


1 answer


Draining the pool "frees" it, it just isn't empty. Think of autorelease pools as stacks, so you're popped out, which means all of these new objects go into the main autorelease pool and aren't cleaned up until the popups show up. Instead, move your autoresource pool creation inside the loop. You can do something like



NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
int i = 0;
while( shouldloop ) {
  // do stuff
  if( ++i%500 == 0 ) {
    [pool drain];
    pool = [[NSAutoreleasePool alloc] init];
  }
}
[pool drain];

      

+5


a source







All Articles