开发者

Releasing an NSDictionary (or other NSObjects) that are a return value.

Let us say that I have a method like this:

- (NSDictionary*)getBigDictionaryOfSecrets
{

NSDictionary *theDic = [[NSDictionary alloc] init];
theDic = // insert conte开发者_运维技巧nts of dictionary

return theDic;
}

How and where should one properly release this?


Try return [theDic autorelease]. This will not release the dictionary immediately, allowing the caller to retain it.


You either autorelease it or you document very well that the caller is responsible for releasing it.


This is exactly what autorelease is for. Do something like this:

- (NSDictionary*)bigDictionaryOfSecrets 
{ 
    NSDictionary *theDic = [[NSDictionary alloc] initWithObjectsAndKeys:@"bar", @"foo", nil];

    return [theDic autorelease];
}

Read more about autorelease in the Memory Management Programming Guide.


Alternatively to the answers provided, instead of using autorelease you could do something like this:

- (void)populateBigDictionaryOfSecrets(const NSMutableDictionary*)aDictionary
{
    // insert contents of dictionary
}

And create/release the dictionary in the class/method where it will be used.


Setting the return object on autorelease should work. Remember that the receiver must retain the returned object.

- (NSDictionary*)getBigDictionaryOfSecrets 
{ 
  NSDictionary *theDic = [[NSDictionary alloc] init];
  theDic = // insert contents of dictionary

  return [theDic autorelease];
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜