2011-06-08 83 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