可能重複:
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