开发者

Deep Copying NSMutableArray Issue [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

deep copy NSMutableArray in Objectiv开发者_JAVA百科e-C ?

I have two arrays of length 5 with items of a custom class I've built. I want to copy the first array into the second. Once copied I want these two arrays to be totally independent (I want to be able to change the first without affecting the second). I have tried several methods to no avail (when I make a change to one, the other is changed as well). They are shown below.

1)

[[NSArray alloc] initWithArray:self.lifelineList copyItems:YES];

My copying protocol for this method is:

- (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]];  

My coding protocol for this method is:

- (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) iterate through the first array, put the instance variables of each element into a temporary variable and then add that variable to the second array.

I am happy to post more code if needed.


  1. Is your custom class properly implementing the NSCopying protocol? (I.e. implement copyWithZone: to return a completely independent instance.)

  2. Is you custom class properly implementing the NSCoding protocol to archive and decode all of the relevant instance variables?

  3. This won't work unless you actually copy the objects themselves. Simply assigning to a temporary variable does nothing at runtime.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜