A work around to the memory leaks in NSXMLParser
Posted by Filip Ekberg on 30 Nov 2010
Lately I've experimenting a bit with parsing XML in Objective-C and discovered something that I'd like to share with you all.
First of all, consider the following "standard" way of downloading an XML and parsing it
NSXMLParser *parser = [[NSXMLParser alloc] 
            initWithContentsOfURL: [NSURL 
            URLWithString:@"http://some-xml-url.com/my.xml"]];
You would think that this line of code is Solid, all it's supposed to do is download the content, release the temporary resources for fetching data and store the final content for the parsing later on. However somewhere in the process there's a resource that isn't cleaned up properly and you will get a memory warning the "Build and Analyze" method wont find it but when you run the application with a Performance tool looking for leaks you will end up getting something like this:
Leaked Object Malloc 512 Bytes
Responsible Frame allocateCollectableUnscannedStorage
Leaked Object NSConcreteMapTable
Responsible Frame +[NSMapTable alloc]
I tried a lot of suggestions to fix this issue some of them being to set the sharedURLCache to 0 like this:
[[NSURLCache sharedURLCache] setMemoryCapacity:0];
[[NSURLCache sharedURLCache] setDiskCapacity:0];
These alone did not solve the problem, so on the quest to find a proper work around I came up with this solution:
[[NSURLCache sharedURLCache] setMemoryCapacity:0];
[[NSURLCache sharedURLCache] setDiskCapacity:0];
NSData *xml = [NSData 
        dataWithContentsOfURL: [NSURL 
        URLWithString:@"http://some-xml-url.com/my.xml"]];
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:xml];;
And that did it, after this I no longer received any memory warnings.
comments powered by Disqus
 Filip Ekberg is a Principal Consultant at fekberg AB in the country with all the polar bears, Microsoft C# MVP, author of a self-published C# programming book, Pluralsight author and overall in love with programming.
Filip Ekberg is a Principal Consultant at fekberg AB in the country with all the polar bears, Microsoft C# MVP, author of a self-published C# programming book, Pluralsight author and overall in love with programming.
                    



