我有一个只读属性,我试图实现NSCopying的对象。它有一个名为“subConditions”(其中包含“SubCondition”对象)的mutableArray。我让它只读,因为我希望调用者能够更改数组中的数据,而不是数组本身。在编写-copyWithZone:方法之前,这一切都非常有效。正确的方法来复制只读NSMutableArray
经过一番摸索之后,我设法得到了一些似乎可行的东西。我不确定这是否是最佳做法。这里是我的-copyWithZone:方法的简化版本:
-(id)copyWithZone:(NSZone*)zone
{
Condition *copy = [[[self class]allocWithZone:zone]init];
NSArray *copiedArray = [[NSArray alloc]initWithArray:self.subConditions copyItems:YES];
[copy.subConditions setArray:copiedArray];
[copiedArray release];
return copy;
}
这是复制readonly mutableArray的正确方法/最佳方法吗?
谢谢你非常详尽的解释! – 2010-06-06 13:35:30
“因为只有NSMutableArrays响应setArray:”NSMutableArrays不回应这种事 – user102008 2011-01-20 23:47:27
@ user102008:是的,他们这样做。 http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html%23//apple_ref/occ/instm/NSMutableArray/setArray%3A – 2011-01-21 04:17:17