I have a Class that I need to copy with the ability to make changes the value of a variable on both Classes. Simply put these classes need to remain clones of each other at all times. My understanding of the documentation is that I can do this using a shallow copy of the Class which has also been declared mutable. By shallow copying the pointer value for the variable will be cloned so that it is an exact match in both classes. So when I update the variable in the original the copy will be updated simultaneously. Is this right?
As you can see below I have used mutableCopyWithZone in the class I want to copy. I have tried both NSCopyObject and allocWithZone methods to get this to work. Although I'm able to copy the class and it appears as intended, when updating the variable it is not changing value in the copied Class.
- (id)mutableCopyWithZone:(NSZone *)zone {
//ReviewViewer *copy = NSCopyObject(self, 0, zone);
ReviewViewer *copy = [[[self class] allocWithZone:zone] init];
copy->infoTextViews = [infoTextViews copy];
return copy;
}
infoTextViews is a property declared as nonatomic, retain in the header file of the class being copied. I have also implemented the NSMutableCopying protocol accordingly.
Any help would be great.
You are right, what you want is a shallow copy, but what you do is a deep copy. Change [infoTextViews copy] to [infoTextViews retain]
Small points.. allocWithZone? You mean allocWithZone:zone ? Plain old alloc would probably be fine.
Why mutableCopyWithZone: ? Are there mutable and immutable versions of ReviewViewer? You probably just want copyWithZone:
Note: If you override copyWithZone to perform a shallow copy you are specifying this behavoir everywhere the object is copied.