Workaround Fix For NSData Crash or Exception During Release in Objective-C

Posted on

I have been moonlighting as an iPhone Developer recently and I can truly say that you will probably spend more time fixing memory leaks in your code than programming for your App in XCode. I was working on a custom (RSS) feed reader and I was determined to keep the memory footprint to less than 30kb because it was a very simple App. I got stuck when I tried to release my feed data inside the NSData class in Cocoa. It crashed even though I tried different methods such as declaring NSURLConnection as an object. This object is probably the largest data stored in memory (can reach about 4MB) in my App because it contains the feed in XML (and not JSON), so it really needs to be released.

 

Here’s how I released the NSData class pointing to a response from NSURLConnection:


NSData *feedData;
feedData = [[NSData alloc] initWithData:[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error]];
feedData = NULL;
[feedData release];

 

You just have to assign NULL to NSData before releasing it. It does work and it minimized my memory use when I checked it in the Leaks Performance Tool in XCode. Even though it works, I am not sure of is why NSData crashes with NSURLConnection explicitly declared as an owned object.