我正在学习如何使用NSCopy。我想制作一个我正在使用的自定义对象的副本,它是UIScrollView中的ImageView。
我正在尝试按如下方式实施NSCopying协议:
-(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;
}
然后在另一个类中复制对象:
ImageView * onePre = [pictureArray objectAtIndex:0];
ImageView * one = [onePre copy];
副本已经制作但是我有一个奇怪的问题。复制对象的ImageView(UIImageView)和ImageToShow(UIImage)属性似乎与原始对象相同。这种方式很有意义,因为在复制代码中我重新指向了一个指针,而不是制作一个新版本的ImageView和ImageToShow。
我的问题是如何制作包含指向其他对象的指针的对象的副本?
谢谢!
答案 0 :(得分:4)
UIView
不符合NSCopying
,但符合NSCoding
:
another.imageView = [NSKeyedUnarchiver unarchiveObjectWithData:
[NSKeyedArchiver archivedDataWithRootObject:self.imageView]];
这会序列化然后反序列化对象,这是在ObjC中执行深层复制的标准方法。
编辑:有关使用此内容的常见-clone
类别方法的示例,请参阅https://stackoverflow.com/a/13664732/97337。