If you don't mind the amount of time it takes for a large graph of objects, and really want to get deep copies of the objects, you can serialize the graph of objects and then deserialize it. The easiest way to do this (assuming all your objects are Foundation Collection objects) is to use the NSPropertyListSerialization class. Serialize your root object to data, then deserialize to your mutable root level array using the NSPropertyListMutableContainersAndLeaves parameter. Your resulting volatile array at the root level will be a deep copy, and all containers will be volatile. It is important to remember that this will indeed be a deep copy, so if you change something in another container, this change will not be reflected in the original objects.
Here is a quick code example:
// Assumes the root-level object is an array, adjust as necessary - (NSMutableArray*)deepMutableCopyOfArray:(NSArray*)array error:(NSError**)outError { NSError* error = nil; NSData* serializedData = [NSPropertyListSerialization dataWithPropertyList:array format:NSPropertyListBinaryFormat_v1_0 options:0 error:&error]; if( !serializedData ) { if( outError ) *outError = error; return nil; } NSMutableArray* mutableCopy = [[NSPropertyListSerialization propertyListWithData:serializedData options:NSPropertyListMutableContainersAndLeaves format:NULL error:&error] retain]; if( !mutableCopy ) { if( outError ) *outError = error; return nil; } return mutableCopy; }
Jason Coco Dec 28 2018-11-12T00: 00Z
source share