I’m trying to eliminate memory leaks from my project, but i’m stuck in 2 situations for days now.
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
if (currentElement) {
[currentElement release];
currentElement = nil;
}
currentElement = [elementName copy];
if ([elementName isEqualToString:@"item"]) {
item = [[NSMutableDictionary alloc] init]; //leak #1
// DOING OTHER STUFF....
//......................
}
}
/*****************************************************************************/
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if ([elementName isEqualToString:@"item"]){
[item setObject:currentTitle forKey:@"title"]; // leak #2
[item setObject:currentLink forKey:@"link"]; //leak #3
[bucket addObject:[item copy]]; // NSMutableArray *bucket
}
}
For leak #1, i tried releasing the item just before memory allocation, but if i do the app crashes. (I mean, just before item = [[NSMutableDictionary alloc] init]; i used
if (item){
[item release];
item=nil;
}
In my dealloc() method, i also have [item release];
For leaks #2 and #3 i have no idea what’s happening.
Note: The 2 methods are called by an xml parser while parsing an XML file, every time an element is read.That is, NSMutableDictionary * item is re-used for every element.
Any suggestions? Thank you in advance 🙂
The general rule, as you seem to know, is that for evey
copy,retain,alloc, ornew, there must also be arelease. I think that you can call[[item copy] autorelease]and remove the preceding check that you have.If that doesn’t fix anything, try checking for
item != nil, instead ofif(item).Also, consider using two other tools, “Build And Analyze” from the “Build” menu, and “NSZombie” to find your other memory leaks. Also, use the Leaks Instumeny to see what library is causing the leak. It may be Apple’s or your own. If it is yours, Leaks will help identify it. Otherwise, it’s not your problem.