Skip to content

Instantly share code, notes, and snippets.

@jjthrash
Last active December 18, 2015 15:39
Show Gist options
  • Save jjthrash/5805749 to your computer and use it in GitHub Desktop.
Save jjthrash/5805749 to your computer and use it in GitHub Desktop.
Dealing with NSURLConnection mystery allocations.

The Problem

Having mystery memory leaks related to NSURLConnection?

One of my clients' projects involves downloading and thumbnailing thousands of images. The basic core of the code is:

for (NSString *key in keys) {
  NSURL *url = [self makeURLForKey:key];
  NSData *data = [NSData dataWithContentsOfURL:url];  // <== this is the line I care about
  [self saveData:data forKey:key];
  NSData *thumbnailData = [self makeThumbnailFromImageData:data];
  [self saveThumbnailData:data forKey:key];
}

The problem with the code is that I was having what I'll call "soft memory leaks." On iPad 1 (yes, customers still run iPad 1) I would get memory crashes on a pretty regular basis. After moving to manual retain/release (it's a non-ARC project for now) as much as possible and wrapping everything else in NSAutoreleasePools, I dug a little deeper using Instruments.

These "soft memory leaks" weren't memory leaks per se, but the number would raise the app's memory usage to 80MB and beyond (danger zone) without my being able to do anything about it. Profiling revealed the offending allocations were coming from the networking code.

The Solution

After a while searching the Interwebs for a solution, I decided to try to see if I could eliminate any caching that might be happening. I added the following code to my app's initialization code (it makes sense for this app.. you decide whether it makes sense for yours):

    [NSURLCache setSharedURLCache:[[[NSURLCache alloc] initWithMemoryCapacity:0
                                                                 diskCapacity:0
                                                                     diskPath:nil] autorelease]];

Bam, no more memory problems. Now the memory usage doesn't appear to grow even a little bit during profiling. So it appears to be caching related. The odd thing is that the default capacity values for +[NSURLCache sharedURLCache] are 512,000 for RAM and 10,000,000 for disk. If this is the case, I'm not sure why I was having memory bloat in the 60MB range. Perhaps a bug.

So, if you're having mystery memory growth when using NSURLConnection, this may be a solution for you.

@McFlyssss
Copy link

You literally saved my day. I've been having memory issues with [NSData dataWithContentsOfURL:url] for several days already and only your post worked!

Thanks for sharing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment