Deep copy Objective-C objects with UIImageView as

2019-07-15 10:37发布

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?

3条回答
ゆ 、 Hurt°
2楼-- · 2019-07-15 11:06

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.

查看更多
时光不老,我们不散
3楼-- · 2019-07-15 11:23

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

查看更多
ゆ 、 Hurt°
4楼-- · 2019-07-15 11:26

Firstly initiate with this

iItem *clone =[[iItem allocWithZone:zone ] init];
查看更多
登录 后发表回答