Search code examples
iphoneobjective-ciosmemory-managementgdataxml

Properly loading and processing XML without memory wasted


I am in the final stages of tweaking my first iphone app for release and am trying to shave off kilobytes where I can. I have a process that syncs some data with my server on start of the app, and I noticed when I commented that out, my app is using 7MB when it is done starting. When I turn it on, it is using 18MB when it is done starting. I am now trying to determine what part of the process is eating the memory and not giving it back. I have turned off most of my sync function and am left with this and it still uses 2MB of memory and does not release it when it is done:

GDataXMLDocument *syncData = [[self getXmlWithUrl:@"http://SOMEURL"] autorelease];

This just uses my helper function to go out and load up a xml document for me to use. My helper function is as follows:

-(GDataXMLDocument*)getXmlWithUrl:(NSString*)url{
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    NSURLResponse *resp = nil;
    NSError *err = nil;
    NSData *response = [NSURLConnection sendSynchronousRequest: theRequest returningResponse: &resp error: &err];
    return [[GDataXMLDocument alloc]initWithData:response options:0 error:&err];
}

I put a release after the syncData is created, but of course it says its already de-allocated. Any ideas on what could be causing this?


Solution

  • Two thoughts.

    1. GDataXMLDocument is a DOM based parse. How big is your response? Typically DOM parses need 2-4x of the original document size in RAM can be even more with certain text encodings. Do you really need DOM parsing? We try and do all of our stuff using SAX so it's progressive and much more memory efficient.

    2. You're using autorelease, so memory won't be released until the autorelease pool is emptied. You could wrap the code with an auto release pool and then dispose of that. http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmAutoreleasePools.html

    Finally, synchronous HTTP requests are generally a bad idea because the performance of the network can be so variable and you'll block the UI thread.