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

来源:互联网 发布:刺客信条枭雄a卡优化 编辑:程序博客网 时间:2024/06/10 23:12
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;}@endNSMutableArray *copiedArray = [resultsArray deepMutableCopy];


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

There are two ways to make deep copies of a collection. You can use the collection’s equivalent ofinitWithArray: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 acopyWithZone: message. If the objects in the collection have adopted theNSCopying 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 theNSCopying 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 inListing 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 ofinitWithArray: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 theNSCoding 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协议