Вопрос

I'm going to manually manage the memory of the NSMutableDictionay, without using autorelease. And every object in the mutableDictonary is a NSArray, every time I add one array in the mutableDictionary, I'm going to use

NSArray *newArray = [[NSArray arrayWithArray:anArray] retain]
[mutableDict setObject:newArray forKey:@"aKey"];

question is, how can I ganrantee that there's no leak of memory? It is good that I directly use [mutableDict release] in the dealloc? does the retainCount of mutableDict equals to the sum of all the retainCounts of its objects(those retained arrays)?

Это было полезно?

Решение

  1. Read the Cocoa Memory Management Guide, no excuses.
  2. The array gets a +1 for your manual retain and another +1 because the dictionary retains it. That’s a leak. Leave out your retain and it will be fine.
  3. Releasing the dictionary in your dealloc is correct. If there are no other strong references to the dictionary, it will get deallocated, releasing all objects contained in it. That means that your array will be deallocated, too, which is probably what you want.
  4. Forget about retainCount.
  5. Really forget about… what was it?

Другие советы

you can:

NSArray *newArray = [NSArray arrayWithArray:anArray];
[mutableDict setObject:newArray forKey:@"aKey"];//mutableDict will auto retain newArray.

you can use Instruments(Leaks) see how much leaks your project have.

You don't need to retain because setObject will already do the retain for you. You just keep the retain on your dictionary as long as you want.

See Reference

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top