Deep NSArray Mutable Copy Category behaviour (nsarray 深度拷贝)

Deep NSArray Mutable Copy Category behaviour
@implementation NSArray (DeepCopy)
- (id)deepMutableCopy {    
    NSMutableArray *mutableCopy = (NSMutableArray *)CFPropertyListCreateDeepCopy(kCFAllocatorDefault, (CFArrayRef)self, kCFPropertyListMutableContainers);
    return mutableCopy;
}
@end
	
@implementation NSDictionary (DeepCopy)
- (id)deepMutableCopy {
    NSMutableDictionary *mutableCopy = (NSMutableDictionary *)CFPropertyListCreateDeepCopy(kCFAllocatorDefault, (CFDictionaryRef)self, kCFPropertyListMutableContainers);
    return mutableCopy;
}
@end
	
NSMutableArray *copiedArray = [resultsArray deepMutableCopy];


以上未起作用~  , 查看apple官方文档解释如下:

There are two ways to make deep copies of a collection. You can use the collection’s equivalent of initWithArray:copyItems: with YES as the second parameter. If you create a deep copy of a collection in this way, each object in the collection is sent a copyWithZone: message. If the objects in the collection have adopted the NSCopying protocol, the objects are deeply copied to the new collection, which is then the sole owner of the copied objects. If the objects do not adopt the NSCopying protocol, attempting to copy them in such a way results in a runtime error. However, copyWithZone: produces a shallow copy. This kind of copy is only capable of producing a one-level-deep copy. If you only need a one-level-deep copy, you can explicitly call for one as in Listing 2.

Listing 2  Making a deep copy

NSArray *deepCopyArray=[[NSArray alloc] initWithArray:someArray copyItems:YES];

This technique applies to the other collections as well. Use the collection’s equivalent of initWithArray:copyItems: with YES as the second parameter.

If you need a true deep copy, such as when you have an array of arrays, you can archive and then unarchive the collection, provided the contents all conform to the NSCoding protocol. An example of this technique is shown in Listing 3

Listing 3  A true deep copy

NSArray* trueDeepCopyArray = [NSKeyedUnarchiver unarchiveObjectWithData:
          [NSKeyedArchiver archivedDataWithRootObject:oldArray]];

需要让自己的类对象实现coding协议


你可能感兴趣的:(Deep NSArray Mutable Copy Category behaviour (nsarray 深度拷贝))