Autorelease pool and memory management
I'm using the following function to put each "facility" node of my XML in a NSMutable array:
-(void) grabXML {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
CXMLDocument *doc = [[[CXMLDocument alloc] initWithData:data options:0 error:nil] autorelease];
NSArray *nodes = [[doc rootElement] nodesForXPath:@"//facilities" error:nil];
for (CXMLNode *itemNode in nodes)
{
for (CXMLNode *eventNode in [itemNode children])
{
if ([[eventNode name] isEqualT开发者_开发百科oString:@"facility"]) {
[content addObject:[eventNode copy]];
}
}
}
loading = FALSE;
[table reloadData];
[pool release];
}
Note that the pool is necessary, 'cause i call the grabXML method in a separate thread.
Using instruments i can see that the following line generates a leak
[content addObject:[eventNode copy]];
And if i change it to
[content addObject:eventNode];
i'm not able to access the XCMLNode later (it seems to be null).
I can avoid the leak putting this on my dealloc method:
for (CXMLNode *node in content) {
[node release];
}
But i think i'm doing something wrong... or at least i'm not aware of what's going on... Please can you give me a clue?
Thanks!
copy
creates an object with a retain count of 1, -addObject:
adds an additional retain, so you have to either release eventNode
after adding it to the array or autorelease the copy:
[content addObject:[[eventNode copy] autorelease]];
You should use
CXMLNode *tempEventNode = [eventNode copy];
[content addObject:tempEventNode];
[tempEvent release];
instead of , [content addObject:[eventNode copy]];
As when you are using [eventNode copy]
it makes retaincount +1
and when you add this copy directly(as in your code) you are increasing it again by +1 as array will retain it. so for arrays retain its not your reponsibility to release but for your copy call you must release it.
[eventNode copy] --> retain count +1
[content addObject:[eventNode copy]]; -> retaincount +2
Thanks
精彩评论