1

I am doing deep copies of NSMutableDictionary with this: https://stackoverflow.com/a/5453600/555690

Like this:

NSMutableDictionary *myCopy = [originalMutableDictionary mutableDeepCopy];

Do I have to release myCopy?

Community
  • 1
  • 1
Saturn
  • 17,888
  • 49
  • 145
  • 271
  • If you create it (or deep copy it), you own it. If you are not using ARC, you need to `autorelease` or `release` your mutable copy. – Robotic Cat Aug 18 '12 at 16:51
  • Robotic Cat is correct. By definition any "copy" function returns an object that is "owned" by you just as if you used alloc/init, and you must release it accordingly. – Hot Licks Aug 18 '12 at 17:56

2 Answers2

4

I'm assuming you're not using ARC. The answer should be "yes" since it's created with copy. See the NARC rules here:

Do you need to release parameters of methods at the end of them in Objective-C?

In that particular code, the ret is created using dictionaryWithObjects so it would already be autoreleased, but then there's an extra retain that's called explicitly. So the answer is... still "yes," which follows the ownership policy.

Community
  • 1
  • 1
Dan Rosenstark
  • 68,471
  • 58
  • 283
  • 421
  • @Omega yes see this line `NSDictionary *ret = [[NSDictionary dictionaryWithObjects:cObjects forKeys:cKeys count:count] retain];` which has an extra retain. The question is why you're not using ARC, which would allow to ignore all this BS...? – Dan Rosenstark Aug 18 '12 at 19:31
2

The code adds a retain to the return value right when it's created and doesn't balance that before returning:

NSMutableArray *ret = [[NSMutableArray arrayWithObjects:cArray count:count] retain];

// The newly-created array retained these, so now we need to balance the above copies
for (unsigned int i = 0; i < count; ++i)
    [cArray[i] release];

return ret;

This is in accordance with Cocoa naming convention and memory management rules, which say that a method with mutableCopy in its name returns an owned value.

The dictionary you get from this method is indeed owned by you and must be released by you.

Note that the middle lines in the snippet above are ensuring that the objects contained in the dictionary are only owned by the dictionary itself; you are not directly responsible for those. They'll be released when the dictionary is destroyed.

jscs
  • 63,694
  • 13
  • 151
  • 195