开发者

iphone how to release memory in this case

开发者 https://www.devze.com 2023-02-28 18:03 出处:网络
I have a method like this - (NSDictionary *)getCellValuesForRow:(int)row { NSMutableDictionary *dictValues= [[NSMutableDictionary alloc] init];

I have a method like this

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

Outage *outage = [listOutage objectAtIndex:row];

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

}

and this value is stored in this way

NSDictionary *dict = [[NSDic开发者_开发问答tionary alloc] initWithDictionary:[self getCellValuesForRow:(indexPath.row-1)]];

how to release memory in this scenario


This is what autorelease is for.

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


You should autorelease dictValues in getCellValuesForRow, or just don't alloc it. This will keep it autoreleased:

NSMutableDictionary *dictValues= [NSMutableDictionary dictionary];

In most cases it should be the responsibility of whatever calls it to alloc it (if it needs to be kept around after the autorelease pool is cleared), then dealloc it later.

If whatever calls it doesn't need it kept around, it can just leave it autoreleased.


An alternative is to simply use

NSMutableDictionary *dictValues= [NSMutableDictionary dictionary];

That's effectively the same thing as what Dan suggested. Just less typing.

It applies to your next line, too:

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

精彩评论

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