Pergunta

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 !

Foi útil?

Solução

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top