2011-06-08 84 views
1

可能重复:
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)遍历第一个数组,将每个元素的实例变量放入一个临时变量中,然后将该变量添加到第二个数组中。

如果需要,我很高兴发布更多的代码。

+0

这应该有所帮助;在过去,我一直使用arrayWithArray:call ... http://stackoverflow.com/questions/3749657/nsmutablearray-arraywitharray-vs-initwitharray – Luke 2011-06-08 18:22:00

+0

@Krypton - 试了一下,没有去。 @Gilles - 我创建了这个问题,因为在该线程中发布的方法对我来说不起作用 – Silvae 2011-06-08 18:41:49

回答

1
  1. 您的自定义类是否正确实施了NSCopying协议? (即,实现copyWithZone:以返回完全独立的实例)。

  2. 是您自定义类是否正确实施NSCoding协议来存档和解码所有相关的实例变量?

  3. 这不会工作,除非您实际上复制对象本身。简单地分配给临时变量在运行时不会做任何事情。

+0

我编辑了问题以显示我的复制/编码协议...也许我做错了他们? – Silvae 2011-06-08 18:28:42

+0

假设'name','email'和'phone'是'NSString'声明为'copy'属性,我认为你的复制/编码方法是正确的。必须有其他事情正在进行。您究竟如何确定深层复制不起作用? – 2011-06-08 18:59:37

+0

即使问题已关闭,我仍然想感谢您的帮助。我发现这个问题(结果与实际的复制过程无关)。 – Silvae 2011-06-08 19:45:33