3
votes

I'm working with NSXMLParser and parsing a number of .xml file in the same class by calling the below method.

[[NSURLCache sharedURLCache] setMemoryCapacity:0];
[[NSURLCache sharedURLCache] setDiskCapacity:0];

NSString *xmlPath = [[NSBundle mainBundle] pathForResource:@"Accessory" ofType:@"xml"];
NSData *xmlData = [NSData dataWithContentsOfFile:xmlPath];

xmlParser = [[NSXMLParser alloc] initWithData:xmlData];
xmlParser.delegate=self;
[xmlParser parse];

also i have deallocated the parser delegate in dealloc method and also released its memory by calling :-

[xmlParser setDelegate:nil];
[xmlParser release];

- (void)dealloc
{
    [xmlParser dealloc];
    [super dealloc];
}

The application is still crashing after parsing two or three xml files in a row. What i'm missing here. Any suggestions would be appreciated. Thanks in advance.

3
What does say Instruments & Leaks?Larme
What reason is given when your application crashes?Tommy
Thank you for your reply!! I have tried with instruments and it shows the alert for allocating the dictionaries that are filling out of xml file for further use in my app. I have also used autorelease for their memory deallocation. But still getting the same issue.Jasveer

3 Answers

2
votes

You cannot be using ARC as calling [super dealloc] would cause a compiler error, so I believe the issue is because you don't use a setter when storing xmlParser. If that code is called multiple times then previously-held references to the NSXMLParser objects would be leaked as you simply abandon them.

The best solution is to ensure xmlParser is a property (a private one declared in the implementation file) and that you call its setter with:

self.xmlParser = [[[NSXMLParser alloc] initWithData:xmlData] autorelease];

and this in dealloc:

self.xmlParser = nil;

removing:

[xmlParser dealloc];

The auto-generated setter will ensure previous references are safely released, stopping the leaks.

1
votes

You your project is ARC enabled then no need to call [xmlParser dealloc] explicitly. Just call:

[xmlParser setDelegate:nil];
xmlParser = nil;

Remove this line from dealloc.

[xmlParser dealloc];
0
votes

You're loading the whole file into RAM at once with +[NSData dataWithContentsOfFile:]. In addition to that the NSData instance you're getting is autoreleased. I.e. it might hang around after you're done.

So you better use initWithContentsOfFile: instead. To further save on memory, you can map the file by passing the option NSDataReadingMappedAlways or NSDataReadingMappedIfSafe.

Alternatively try using a stream for the file contents. So create your parser with -[NSXMLParser initWithStream:].

We don't know what objects you're creating in the delegate. They might be eating up all the memory.