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.
Is your custom class properly implementing the
NSCopying
protocol? (I.e. implementcopyWithZone:
to return a completely independent instance.)Is you custom class properly implementing the
NSCoding
protocol to archive and decode all of the relevant instance variables?This won't work unless you actually copy the objects themselves. Simply assigning to a temporary variable does nothing at runtime.
精彩评论