Pergunta

I've created a model that has mainly a nested array of custom objects for use in a split-view (both UITableViews) "to-do" list type app. The left (master) is the lists of lists and the right (detail) is the lists :) Some other variables are kept in some of the classes like isSelected, isExpanded...

All of these classes implement NSCopying protocol. When I make a copy of a master list item and change the copy's name that works, but if I change anything in the detail list item belonging to that master list item, it changes in both the copy and the original. So I guess my question is how do I create a deep copy of a master list item. I thought by making them all implement NSCopying protocol it would automatically do this. I I really don't know what to put for code with so anything you need just ask.

Foi útil?

Solução

Take a look at NSKeyedArchiver - you can archive your array of arrays, unarchive it, and you have a deep copied clone.

(Of course this only works if all your objects support archiving.)

Outras dicas

how do I create a deep copy of a master list item

By implementing the deep copy logic in your own code. Deep copies are typically -- sometimes, but generally not -- more than just doing a copy of every object in the collection and everything it is connected to. Outside of property lists, anyway, which do support deep copies, but are limited to very simple, non-cyclic object graphs.

So, you would iterate the collection and copy each item in the collection, as needed. While implementing copyWithZone: may seem reasonable, a deep copy is often done by manually instantiating new instances and setting the various attributes based on the original as needed, copying where required.

-(MyClass)deepCopy {
    MyClass* theCopy = [self mutableCopy];
    for (MyElementType* element in self.dataContainer) {
        MyElementType* theCopiedElement = [element deepCopy];
        [theCopy somehowInsertThisElementInTheRightPlace:theCopiedElement]l
    }
    return theCopy;
}

Obviously, there's a bit of magic involved in that 5th line -- exactly how you do it depends on how the subsidiary data items are attached to your object. But there are really only 3-4 basic scenarios. Recursion naturally handles everything else.

(And note that you can be "smart" and not copy immutable objects, etc.)

(Also note that you can create "categories" for NSMutableArray and NSMutableDictionary.)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top