2013-04-04 38 views
2

我正在學習如何使用NSCopy。我想製作一個我正在使用的自定義對象的副本,這是UIScrollView中的一個ImageView。使用NSCopy複製包含指針的自定義對象?

我想實現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

UIImageView和UIImage不符合NSCopying,如果你想複製它們,你必須實現它到你自己的類別。 – 2013-04-04 11:50:02

+0

啊,想知道這是否是答案 - 謝謝。 – GuybrushThreepwood 2013-04-04 12:33:27

回答

4

UIView不符合NSCopying,但它確實符合NSCoding

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

這種序列化和反序列化,然後將對象,這是在ObjC執行深拷貝的標準方式。


編輯:參見https://stackoverflow.com/a/13664732/97337爲使用此共同-clone類方法的一個例子。

+0

與UIImageView和UIImage上的類別結合使用。這個工作到底如何,僅僅是爲了我的理解? – GuybrushThreepwood 2013-04-04 12:49:44

+0

有關完整詳細信息,請參閱https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Archiving/Archiving.html。 'NSCoding'意味着一個對象可以被序列化(就像Java中的Serializable一樣)。所以你只需序列化對象,然後立即反序列化這個對象,然後你就完成了一個完整的拷貝。視圖具體可序列化,因爲這是它們如何存儲在nib文件中。 – 2013-04-04 13:27:09

相關問題