2

I am learning how to use NSCopy. I want to make a copy of a custom object I am using, which is an ImageView in a UIScrollView.

I am trying to implement NSCopying protocol as follows :

-(id)copyWithZone:(NSZone *)zone
{
    ImageView *another = [[ImageView allocWithZone:zone]init];

    another.imageView = self.imageView;
    another.imageToShow = self.imageToShow;
    another.currentOrientation = self.currentOrientation;
    another.portraitEnlarge = self.portraitEnlarge;
    another.landscapeEnlarge = self.landscapeEnlarge;
    another.originalFrame = self.originalFrame;
    another.isZoomed = self.isZoomed;
    another.shouldEnlarge = self.shouldEnlarge;
    another.shouldReduce = self.shouldReduce;
    another.frame = self.frame;
    //another.delegate = another;
    another.isZoomed = NO;

    [another addSubview:another.imageView];

    return another;
}

Then to copy the object in another class :

ImageView * onePre = [pictureArray objectAtIndex:0];
ImageView * one = [onePre copy];

The copy is made however I have one odd problem. The copied object's ImageView (a UIImageView) and ImageToShow (a UIImage) properties seem to be the same as the original objects. This kind of makes sense as in the copy code I am re-pointing a pointer, rather than making a new version of ImageView and ImageToShow.

My question is how do I make a copy of an object that contains pointers to other objects ?

Thanks !

Ramy Al Zuhouri
  • 21,580
  • 26
  • 105
  • 187
GuybrushThreepwood
  • 5,598
  • 9
  • 55
  • 113

1 Answers1

4

UIView does not conform to NSCopying, but it does conform to NSCoding:

another.imageView = [NSKeyedUnarchiver unarchiveObjectWithData:
                      [NSKeyedArchiver archivedDataWithRootObject:self.imageView]];

This serializes and then deserializes the object, which is the standard way to perform a deep copy in ObjC.


EDIT: See https://stackoverflow.com/a/13664732/97337 for an example of a common -clone category method that uses this.

Community
  • 1
  • 1
Rob Napier
  • 286,113
  • 34
  • 456
  • 610
  • Works a charm combined with a category on UIImageView and UIImage. How exactly does this work just for my understanding ? – GuybrushThreepwood Apr 04 '13 at 12:49
  • See https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Archiving/Archiving.html for full details. `NSCoding` means that an object can be serialized (like Serializable in Java). So you just serialize the object and then immediately deserialize the object, and you wind up with a complete copy. Views are specifically serializable since this is how they are stored in nib files. – Rob Napier Apr 04 '13 at 13:27