Deep copy Objective-C objects with UIImageView as

2019-07-15 11:09发布

问题:

I have an object with properties that are NSString, UIImageView and simple vars like BOOL, int and float.

I'm trying to create a deep copy of the object. For that I've implemented the NSCopying protocol to my class and the copyWithZone method like:

-(id)copyWithZone:(NSZone *)zone
{
    iItem *clone = [[iItem alloc] init];

    //iItem *clone = [super copyWithZone:zone];

    clone.originalTransform = self.originalTransform;
    clone.initialTransform = self.initialTransform;
    clone.originalFrame = self.originalFrame;

    clone.zOrder = self.zOrder;
    clone.itemId = self.itemId;
    clone.itemIdColor = self.itemIdColor;
    clone.itemIdTexture = self.itemIdTexture;
    clone.itemIdStyle = self.itemIdStyle;
    clone.textureLevel = self.textureLevel;
    clone.currentSizePercent = self.currentSizePercent;
    clone.holdItem = self.holdItem;
    clone.isInverted = self.isInverted;
    clone.delegate = self.delegate;
    clone.mergedFrame = self.mergedFrame;

    clone.selectedMergeView = [self.selectedMergeView copy];

    clone.ScaleFactorScreen = self.ScaleFactorScreen;

    clone.selectedFrameView = [self.selectedFrameView copy];
    clone.selectedFrame = [self.selectedFrame copy];
    clone.frameBeforeMovement = self.frameBeforeMovement;

    //clone.touchBeginPoints = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);
    clone.touchBeginPoints = CFDictionaryCreateMutableCopy(NULL, 0, self.touchBeginPoints);

    clone.contentMode = UIViewContentModeScaleAspectFit;
    clone.animationImages = self.animationImages;
    clone.image = [self.image copy];
    clone.animationDuration = self.animationDuration;
    clone.animationRepeatCount = self.animationRepeatCount;
    [clone startAnimating];


    clone.transform = self.transform;

    clone.frame = self.frame;

    clone.userInteractionEnabled = YES;
    clone.multipleTouchEnabled = YES;

    return clone;
}

The class iItem inherits from UIImageView class, so I tried to call super copyWithZone but I'm getting error. And for the UIImageView objects that I'm trying to clone I receive the SIGABRT message '-[UIImageView copyWithZone:]: unrecognized selector sent to instance 0x210f50'.

How can I make a deep copy of an object that have UIImageViews, NSString and simple vars?

回答1:

I think you're doing everything right, perform the 'copy' selector on objects that implement NSCopying, and manually set properties (like you did for image, content mode etc) for those that don't.



回答2:

Easiest way is to archive with NSKeyedArchiver and unarchive to NSKeyedUnarchiver assuming your objects conform to NSCoder



回答3:

Firstly initiate with this

iItem *clone =[[iItem allocWithZone:zone ] init];