Who is responsible for releasing objects in an array when copying?
cocoa, memory-management, nsarray, objective-c
Solution
I think the previous answers have missed the point, or else the asker was pretty unclear. The actual question isn't talking about either array, but rather the array contents:
who is responsible for releasing the objects contained in the array? Is it main() or array2?
Both `array1` and `array2` are responsible for releasing the objects.
From the NSArray documentation:
"Arrays maintain strong references to their contents—in a managed memory environment, each object receives a retain message before its id is added to the array and a release message when it is removed from the array or when the array is deallocated."
To begin with, each of the objects are retained by the NSArray `array1`. When you create `array2` via `-mutableCopy`, you get an NSMutableArray which points to the same objects, and retains each of them again. If you were to release `array1` at this point, when its `dealloc` method were called it would release each of the objects it contains. However, `array2` has retained them, so the objects won't be destroyed — only when their retain count reaches 0, which would happen if `array2` were destroyed and nobody else has retained any of the objects (or when they are removed from `array2`).
Since collection classes (arrays, sets, dictionaries, etc.) handle retaining and releasing their contents, all you have to worry about is retaining or releasing the collection itself. Since you used `-mutableCopy`, remember that you have implicitly retained `array2`, so you should release it when you're done with it.
Problem
In Objective-C, if array1 is copied onto array2 using mutableCopy, and suppose the code is done in main(), who is responsible for releasing the objects contained in the array? Is it main() or array2?