可能重复:
deep copy NSMutableArray in Objective-C ?深度复制NSMutableArray的问题
我有我已经建立了一个自定义类的项目长度为5的两个数组。我想将第一个数组复制到第二个数组中。一旦复制,我希望这两个数组完全独立(我希望能够在不影响第二个的情况下更改第一个数组)。我尝试了几种方法无济于事(当我改变一个,另一个也改变了)。它们如下所示。
1)
[[NSArray alloc] initWithArray:self.lifelineList copyItems:YES];
该方法我复制协议是:
- (id) copyWithZone:(NSZone *)zone{
Lifeline *lifelineCopy = [[Lifeline allocWithZone:zone]init];
lifelineCopy.name = name;
lifelineCopy.phone = phone;
lifelineCopy.email = email;
lifelineCopy.isActive = isActive;
lifelineCopy.contactID = contactID;
return lifelineCopy;
}
2)
[NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject: self.lifelineList]];
我给这方法编码协议是:
- (id) initWithCoder:(NSCoder *)aDecoder{
if (self=[super init]){
self.name = [aDecoder decodeObject];
self.phone = [aDecoder decodeObject];
self.email = [aDecoder decodeObject];
self.contactID = [aDecoder decodeIntegerForKey:@"contactID"];
self.isActive = [aDecoder decodeIntegerForKey:@"isActive"]>0;
}
return self;
}
- (void) encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:self.name];
[aCoder encodeObject:self.phone];
[aCoder encodeObject:self.email];
[aCoder encodeInteger:self.contactID forKey:@"contactID"];
[aCoder encodeInteger:(NSInteger)self.isActive forKey:@"isActive"];
}
3)遍历第一个数组,将每个元素的实例变量放入一个临时变量中,然后将该变量添加到第二个数组中。
如果需要,我很高兴发布更多的代码。
这应该有所帮助;在过去,我一直使用arrayWithArray:call ... http://stackoverflow.com/questions/3749657/nsmutablearray-arraywitharray-vs-initwitharray – Luke 2011-06-08 18:22:00
@Krypton - 试了一下,没有去。 @Gilles - 我创建了这个问题,因为在该线程中发布的方法对我来说不起作用 – Silvae 2011-06-08 18:41:49