开发者

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

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 setObje开发者_如何学Pythonct:@"My Name" forKey:@"name"];

How to avoid memory leak here ?

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


  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.


alternative solution

-(NSMutableDictionary *)returnningMyMutableDictionary{

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

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


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];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜