mutable copy confusion

Hi All,

I have an NSarrayController “Backset” which controls an array of dictionaries of various values. I have it set up so one can duplicate one of the members and create a new (similar) set of values. I used mutableCopy thinking that would make a new copy but the values in the new set point to the original ones so any changes to that array are reflected in the first. I always thought making a mutable copy would create an entirely new array in memory.

on makeDuplicateSet_(sender)
        set indexnum to Backset's selectionIndex()
        set thisObj to Backset's arrangedObjects's objectAtIndex_(indexnum)
        set newObj to thisObj's mutableCopy()
        set theSetTitle to newObj's objectForKey_("backupset") as string
        set theSetTitle to theSetTitle & " copy" as text
        newObj's setObject_forKey_(theSetTitle,"backupset")
        Backset's addObject_(newObj)
 end makeDuplicateSet_

Cheers, rob

When you use mutableCopy with an array, you make a copy of the array – not of the objects in the array. As you found, it doesn’t perform a deep copy.

The easiest way to make a deep copy is to archive the array and then unarchive the archive. So:

set arrayCopy to current application's NSKeyedUnarchiver's unarchiveObjectWithData:(current application's NSKeyedArchiver's archivedDataWithRootObject:anNSArray)

The limitation is that all members of the array must support the NSCoding protocol. That includes most of the common classes, but not NSObject or classes you make by subclassing NSObject (unless you add the code to support it).

Ah yes - I had a feeling NSArchiving was in there somewhere.

Thanks Shane! Rob