Friday, May 6, 2011

When release NSXMLParser ?

Hello all,

I am using NSXMLParser like this :


- (BOOL)parseXMLData:(NSData *)inData
{
 provisioningParser = [[NSXMLParser alloc] initWithData: inData]; // defined if .h
[provisioningParser setDelegate:self]; [provisioningParser setShouldProcessNamespaces:NO]; [provisioningParser setShouldReportNamespacePrefixes:NO]; [provisioningParser setShouldResolveExternalEntities:NO];

return [provisioningParser parse]; }

My question is when should I release NSXMLParser? I believe it is automatically released when parsing is finished; is this true? If yes, instruments indicate there is a leak.

Do you have an idea ?

Thanks

From stackoverflow
  • Since you alloc'd it, you'll need to release it. Just release it after calling parse:

    BOOL rval = [provisioningParser parse];
    [provisioningParser release];
    return rval;
    

    Also, from the looks of your code, it looks like you might be saving this in a member variable. Is there a reason for doing that? If not, make it a local variable. If so, you'll probably want to release it in the dealloc() method of your class instead of after calling parse().

    thierryb : Something strange happens. My app crash when I release parser after parse call. Is it possible that the parser is released on parserDidEndDocument delegate function ? Here the backtrace : in objc_msgSend () in NSPopAutoreleasePool () in _UIApplicationHandleEvent () in SendEvent () in PurpleEventTimerCallBack () in CFRunLoopRunSpecific () in CFRunLoopRunInMode () in GSEventRunModal () in GSEventRun () in -[UIApplication _run] () in UIApplicationMain ()
    thierryb : sorry for the string format...
  • The correct thing to do is to release it within the dealloc method since it's an instance variable. But your code is wrong for that scenario. Imagine calling parseXMLData: twice in a row. provisioningParser will be overwritten the second time, making it impossible to release it within your dealloc.

    If you want it to be local, declare it local, and end the method with

    return [[provisioningParser autorelease] parse];
    

    You could allocate it with NXSMLParser 'parserWithData:' and not have to do any of this (still should move it local to the method though).

0 comments:

Post a Comment