Question

Apple's NSCopying docs state that copyWithZone: returns an object that's implicitly retained by the sender. So when that object is added to an NSMutableArray it seems like the object should be sent an autorelease message to keep the retain count balanced (since the array will retain the object).

So to deep copy the contents of one array to another I'd expect something like:

NSMutableArray *destination = [NSMutableArray array];

// assume MyObject adopts NSCopying
for (MyObject *obj in myArray) 
    [destination addObject:[[obj copy] autorelease]];

However I noticed a different approach in this answer. It seems like [ret addObject:[val copy]] is a memory leak. However I'm brand new to NSCopying so I thought I'd ask: When adding a copied object to an array should the object be sent an autorelease message to keep the retain count balanced?

Edit - more info: Clang reports a potential memory leak after removing the autorelease. Perhaps the linked answer assumes copy returns an object that's not implicitly retained by the sender.

Was it helpful?

Solution

Yes it does need to be released but I wouldn't use autorelease in a loop like that, do it manually with each iteration

   for (MyObject *obj in myArray)
    {
        MyObject *copy = [obj copy];
        [destination addObject:copy];
        [copy release];
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top