1
NSURL *url = [[NSURL alloc] initWithString:@"http://www.someurl.com/sample.xml"];
xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];
[url release];

XMLParser *parser = [[XMLParser alloc] initXMLParser];        //50.0%


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

[xmlParser parse];                                           //50.0%
[xmlParser release];

This is my parsing code and the leaks instrument is showing leaks. I really dont know what's wrong or how to fix this. Any suggestions?

Spire
  • 1,055
  • 2
  • 17
  • 47

3 Answers3

3
parser = nil;
[parser release];

...this does not do what you think it does. Assuming parser is a property, then self.parser = nil and parser = nil do very different things. The former will call the parser setter method, which will release the old value and set the property to nil. The latter just changes the pointer from its current location to nil.

By setting the pointer to nil you have lost the reference to the object, so you've instantly leaked the object that was previous assigned to it - you are basically trying to release a nil object. You need to remove the nil call, or place it after the release (see below).

You may be thinking of setting a pointer to nil after you have released it, to prevent problems should you try and access it at some point in the future.

Here are a few other questions to help provide some context:

release Vs nil -- Best Practice

Difference between release and release then set to nil

Community
  • 1
  • 1
lxt
  • 31,146
  • 5
  • 78
  • 83
  • I would rewrite it to a one-liner: `[parser release], parser = nil;`. Although it's local scope, it isn't really necessary to set the pointer to `nil` – Joost Aug 24 '11 at 13:56
  • Indeed - personally, I only set properties to nil, not local variables. And, as Simon suggests in his answer, this won't fix leaks with the parser itself! – lxt Aug 24 '11 at 13:58
2

I have had similar issues with using NSXMLParser, but found an easy fix to resolve the memory leak.

Instead of doing

xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];

Do the following

NSData *xmlData = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]]; 
xmlParser = [[NSXMLParser alloc] initWithData:xmlData];

I was able to get rid of my memory leaks

Frank
  • 3,376
  • 1
  • 23
  • 23
0

There's a similar post here about leaks in the parser. I also have this issue. it's annoying but it's not a huge leak so I don't worry too much about it. Will see if iOS 5 fixed the problem (if it is indeed a known leak)

Edit: I'm now interested to see if I made the mistake above!

Community
  • 1
  • 1
Simon
  • 8,981
  • 2
  • 26
  • 32