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

iPhoneI 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.


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

  1. The fix worked for me!!! :)

  2. Thanks for sharing the code on how to do this. Memory leaking is always an issue that needs to be fixed especially when coding for the Iphone.

  3. I really appreciate your having shared this code with us. I’m very impressed to read this blog of technology based material because everyone knows about the success of the thing however very few people are aware about the process of succeeding.

Leave a Reply

Go to top