Srini Srini - 3 months ago 21
iOS Question

Objective memory leaks when copying objects

I have a sample app that looks like a social network iOS app. I am new to cocoa framework so I'm studying the sample code. Upon hitting analyze, there are 255 reported memory leaks in the app. I was able to solve around 100 of the leaks which were very simple, but I cannot solve the rest.

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
//DLog(@"found this element: %@", elementName);
currentElement = [elementName copy];
if([MethodName isEqualToString:@"SignInStep"])
{

if ([elementName isEqualToString:@"item"])
{ // clear out our story item caches...
item = [[NSMutableDictionary alloc] init];
currentUserId = [[NSMutableString alloc] init];

currentError = [[NSMutableString alloc] init];
}

}

}


Allocation of variables for the item:

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
//DLog(@"ended element: %@", elementName);

if([MethodName isEqualToString:@"SignInStep"])
{
if ([elementName isEqualToString:@"item"])
{ // save values to an item, then store that item into the array...
[item setObject:currentUserId forKey:@"userId"];

[item setObject:currentError forKey:@"error"];

[SignIn addObject:[item copy]]; //Method returns Objective C Object with +1 retain count

}
}

}//Object leaked: allocated object is not referenced later in this execution path and has a retain count of +1


I received the following errors:


1) Method returns Objective C Object with +1 retain count

2) Object leaked: allocated object is not referenced later in this execution path and has a retain count of +1


I have mentioned in the above code where exactly I received these leaks. Can anyone tell me what is causing this?

Answer

You must relinquish ownership of an object you own

id obj =  [item copy];
[SignIn addObject:obj]; // SignIn will retain obj 
[obj release];  

Take a look at Memory Management Programming Guide

        item = [[NSMutableDictionary alloc] init]; // release this object
        currentUserId = [[NSMutableString alloc] init]; // release this object

        currentError = [[NSMutableString alloc] init]; // release this object
Comments