views:

125

answers:

1

Hello, I am using a NSXMLParser class in my program and I assign a delegate to it. This delegate, though, gets retained by the setDelegate: method resulting to a minor, yet annoying :-), memory leak.

I cannot release the delegate class after the setDelegate: because the program will crash.

Here is my code:

self.parserDelegate = [[ParserDelegate alloc] init]; //retainCount:1
self.xmlParser = [[NSXMLParser alloc] initWithData:self.xmlData];
[self.xmlParser setDelegate:self.parserDelegate]; //retainCount:2
[self.xmlParser parse];
[self.xmlParser release];

ParserDelegate is the delegate class.

Of course if I set 'self' as the delegate, I will have no problem but I would like to know if there is a way to use a different class as delegate with no leaks.

Thank you in advance.

+2  A: 

From the documentation on setDelegate:

"An object that is the new delegate. It is not retained. The delegate must conform to the NSXMLParserDelegate Protocol protocol."

So no worries. Additionally, even if it was retained, a proper NSXMLParser class would release the delegate in 'dealloc'. So I don't think you have a leak.

The reason you're crashing, is you are deallocating the delegate, since you bring the retain count down to 0.

bobDevil
So I shouldn't worry even if it shows as a leak in Instruments?Also, since I get to retainCount:2 after the 'setDelegate:' method (according to Instruments), when does the count go to 0?
dizzy_fingers
That is very strange that you get a second retain. You say it crashes if you have that release in the code up above, or when you add a second release to counteract the 2 retain count? If the latter, it sounds like something else is retaining it.
bobDevil
The first. It crashes if I release it right after the [self.xmlParser release]. Could it be some bug in the Instruments tool? I can't seem to understand how the 'setDelegate' retains the delegate...
dizzy_fingers
Oh! I know (sorry for the delay). How is your 'parserDelegate' property defined? When you access it via 'self.parserDelegate' it will retain it, then autorelease it, hence the retain count of 2. However, if you release it, you will crash the next time the autorelease pool drains (likely the next time the event loop runs)
bobDevil
Yes, I access it via 'self.parserDelegate'. So, now it makes complete sense.Thank you for your help bob :-).
dizzy_fingers