iphone如何在这种情况下释放内存

时间:2011-04-22 20:23:15

标签: iphone memory-leaks

我有这样的方法

- (NSDictionary *)getCellValuesForRow:(int)row {
NSMutableDictionary *dictValues= [[NSMutableDictionary alloc] init];

Outage *outage = [listOutage objectAtIndex:row];

[dictValues setObject:outage.duration forKey:@"OutageDuration"];
   return dictValues;

}

并且此值以这种方式存储

NSDictionary *dict = [[NSDictionary alloc] initWithDictionary:[self getCellValuesForRow:(indexPath.row-1)]];

如何在此场景中释放内存

3 个答案:

答案 0 :(得分:2)

这是autorelease的用途。

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

答案 1 :(得分:1)

你应该在getCellValuesForRow中自动释放dictValues,或者只是不分配它。这将使其自动释放:

NSMutableDictionary *dictValues= [NSMutableDictionary dictionary];

在大多数情况下,它应该由它分配它的任何调用负责(如果它需要在自动释放池被清除后保留),然后再解除它。

如果它不需要它的任何调用,它可以让它自动释放。

答案 2 :(得分:0)

另一种方法是简单地使用

NSMutableDictionary *dictValues= [NSMutableDictionary dictionary];

这与Dan建议的实际上是一回事。只需减少打字。

它也适用于你的下一行:

NSDictionary *dict = [NSDictionary dictionaryWithDictionary:[self getCellValuesForRow:(indexPath.row-1)];
相关问题