Memory leak in DDXML parser
-
30-06-2021 - |
質問
I load data from Internet, and parse it using DDXML parser in another thread. Here is code (callback connectionDidFinishLoading: is coming in background thread, I scheduled URLConnection at background thread):
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"connection did finish load");
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
DDXMLDocument *xdoc = [[DDXMLDocument alloc] initWithData: receivedXmlData options:0 error: NULL];
NSLog(@"document retainCount1 = %d", [xdoc retainCount]);
NSArray *nodes = [xdoc selectNodes: @"./items/item"];
NSLog(@"document retainCount2 = %d", [xdoc retainCount]);
for (DDXMLElement *tabXmlItem in nodes)
{
// here is the parsing
}
NSLog(@"document retainCount3 = %d", [xdoc retainCount]);
[xdoc release];
[receivedXmlData setLength:0];
[pool drain];
[pool release];
}
I see in memory allocator: DDXMLDocuments, DDXMLNodes, DDXMLElements still living after the end of parsing. So, there's big amount of CFString and CFData in the memory. Why these objects aren't cleared? Maybe, I use autorelease pool wrongly or DDXML parser is with surprise?
解決
retainCount
is useless. Don't call it. http://whentouseretaincount.com/
No need to both drain
and release
the pool; just drain
it.
Better yet, use @autoreleasepool {...}
around the pool's scope.
Since you are using the Allocations instrument, turn on "track reference counts". Then you can look at the history of retains/releases on the objects that are sticking around and see why they are still around.