本文介绍了如何在Objective-C中进行深拷贝?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在学习ios开发,并且对Objective-C中的深层复制感到困惑.例如,我下面有三个班.现在我想深入复制ClassA,有人可以教我完成复制方法吗?
I'm learning ios development and I'm confused with deep copying in Objective-C.For example,I have three class below. Now I want to deep copy ClassA, can anybody teach me to finish the copy method?
A:
@interface ClassA : NSObject <NSCopying>
@property (nonatomic, assign) int aInt;
@property (nonatomic, retain) ClassB *bClass;
@end
B:
@interface ClassB : NSObject <NSCopying>
@property (nonatomic, assign) int bInt;
@property (nonatomic, retain) ClassC *cClass;
@end
C:
@interface ClassC : NSObject <NSCopying>
@property (nonatomic, assign) int cInt;
@property (nonatomic, copy) NSString *str;
@end
推荐答案
您应该在要复制的每个类中添加copyWithZone:
方法.
You should add the copyWithZone:
method in each class you want to be copiable.
注意:我是手工写的,要注意打字错误.
NB: I wrote this by hand, watch out for typos.
-(id) copyWithZone:(NSZone *) zone
{
ClassA *object = [super copyWithZone:zone];
object.aInt = self.aInt;
object.bClass = [self.bClass copyWithZone:zone];
return object;
}
-(id) copyWithZone:(NSZone *) zone
{
ClassB *object = [super copyWithZone:zone];
object.bInt = self.bInt;
object.cClass = [self.cClass copyWithZone:zone];
return object;
}
-(id) copyWithZone:(NSZone *) zone
{
ClassC *object = [super copyWithZone:zone];
object.cInt = self.cInt;
object.str = [self.str copy];
return object;
}
这篇关于如何在Objective-C中进行深拷贝?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!