0
votes

Can i release an object (created in a method) in another method (without retaining) in objective C ?

My code is as follows

-(NSMutableDictionary *)returnningMyMutableDictionary{

NSMutableDictionary *myDict = [[NSMutableDictionary alloc] init];

[myDict setObject:@"My Name" forKey:@"name"];

[myDict setObject:@"99" forKey:@"age"];

return myDict;

}

-(void)mainmethod{

NSMutableDictionary *dict = [self returnningMyMutableDictionary];

NSLog(@"dict %@",dict);

dict = nil;

[dict release];

}

Q1) Is it good practice to release the returning dictionary in "mainmethod" ?

Q2) When i run the application in instrument , i am getting leak in following portion.

[myDict setObject:@"My Name" forKey:@"name"];

How to avoid memory leak here ?

Please help me..Thanks in advance for your help..

3
dict = nil; [dict release]; You aren't releasing dict here, but nil.Alex Brown
means "[dict release];" doesn't have any effect ?S.P.
Thanks for answers to all....S.P.

3 Answers

4
votes
  1. autorelease from the first function.

    return [myDict autorelease];

  2. don't assign dict to nil before you release it. That's your memory leak. In fact, now it's autoreleased, don't release it at all.

1
votes

alternative solution

-(NSMutableDictionary *)returnningMyMutableDictionary{

NSMutableDictionary *myDict = [[[NSMutableDictionary alloc] init] autorelease];

and now alex saying correct first release object then assign nil;

1
votes

There is nothing wrong releasing an allocated object from another method as long as that method is responsible for creating the object in the first place.

It might look like this is not the case in your example, but if you look between the lines the mainmethod is the method that requests for a new NSMutableDictionary.

In that sense you should follow the naming pattern of adding new/alloc in your method responsible for creating a new object.

You usually do retain the object and release it in dealloc but you that's not always the case.

In general avoid using autorelease if you have control over releasing the object.

-(NSMutableDictionary *)allocMutableDictionary
{
    NSMutableDictionary *myDict = [[NSMutableDictionary alloc] init];
    [myDict setObject:@"My Name" forKey:@"name"];
    [myDict setObject:@"99" forKey:@"age"];

return myDict;
}

-(void)mainmethod
{
    NSMutableDictionary *dict = [self allocMutableDictionary];

    NSLog(@"dict %@",dict);

    dict = nil; //making the dict nil means you don't actually release it in the next line
    [dict release];
}