假设我有一个这样的方法:
- (NSDictionary*)getBigDictionaryOfSecrets
{
NSDictionary *theDic = [[NSDictionary alloc] init];
theDic = // insert contents of dictionary
return theDic;
}
应该如何以及在哪里正确地释放它?
尝试return [theDic autorelease]
。这不会立即释放字典,允许调用者retain
它。
你要么自动释放它,要么很好地记录调用者负责释放它
这正是autorelease
的作用。像这样做:
- (NSDictionary*)bigDictionaryOfSecrets
{
NSDictionary *theDic = [[NSDictionary alloc] initWithObjectsAndKeys:@"bar", @"foo", nil];
return [theDic autorelease];
}
在内存管理编程指南中阅读更多关于autorelease
的信息
对于所提供的答案,您可以这样做,而不是使用autorelease
:
- (void)populateBigDictionaryOfSecrets(const NSMutableDictionary*)aDictionary
{
// insert contents of dictionary
}
并在使用字典的类/方法中创建/释放字典
将返回对象设置为自动释放应该可以工作。记住,接收方必须保留返回的对象。
- (NSDictionary*)getBigDictionaryOfSecrets
{
NSDictionary *theDic = [[NSDictionary alloc] init];
theDic = // insert contents of dictionary
return [theDic autorelease];
}