I have an NSMutableArray of custom objects (based on NSObject) which I want to copy into a new array. But I want it to be a deep copy.
How do I go about doing this? Do I need to implement the NSCopying protocol in my custom object?
Thanks
I have an NSMutableArray of custom objects (based on NSObject) which I want to copy into a new array. But I want it to be a deep copy.
How do I go about doing this? Do I need to implement the NSCopying protocol in my custom object?
Thanks
是的,您需要表明您的自定义类遵守NSCopying
协议,然后您实现该copyWithZone:
方法。这允许复制您的课程。在您的实现中,copyWithZone:
您需要确定有多少内部结构还需要深度复制。
现在,如果您对数组进行深层复制,新数组将包括对象的复制版本,而不仅仅是对原始对象的引用。
请注意,数组的常规副本不会进行深度复制。要制作深层副本,您需要以下内容:
NSArray *deepCopyArray=[[NSArray alloc] initWithArray:someArray copyItems:YES];
可以通过手动遍历所有元素来深度复制数组。如果对象需要进一步的深度复制,这是必要的。
NSMutableArray *deepCopied = [NSMutableArray arrayWithCapacity:[array count]];
// assumes your objects know how to "deepCopy"
for (id object in array)
{
// if not ARC or GC:
[deepCopied addObject:[[object deepCopy] aurorelease]];
// if ARC or GC
[deepCopied addObject:[object deepCopy]];
}
否则:
NSArray *deepCopied = [[NSArray alloc] initWithArray:array copyItems:YES];
如果您需要制作大量深拷贝,此处的答案中描述了一种类别方法可能会有所帮助。