Swift中使用copy方法来复制对象
2016-09-27 本文已影响0人
jezong
在swift中,NSObject的子类可以使用copy方法来复制实例对象,做法如下:
- 子类必须声明并实现
NSCopying协议; - 子类实现
copyWithZone:方法; - 子类的构造方法
init必须使用requried关键字修饰
示例代码:
class ClazzA: NSObject, NSCopying {
var memberA = 0
//必须使用required关键字修饰
required override init() {
}
///实现copyWithZone方法
func copyWithZone(zone: NSZone) -> AnyObject {
let theCopyObj = self.dynamicType.init()
theCopyObj.memberA = self.memberA
return theCopyObj
}
}
ClazzA类直接继承NSObject,并且也实现了NSCopying的copyWithZone方法,所以调用copy方法来复制ClazzA对象是没有问题的。但是考虑到ClazzA可以作为其他类的基类,那么第12行代码let theCopyObj = self.dynamicType.init()就不能替换成let theCopyObj = ClazzA(),否则子类中强制类型转换时将发生异常。应该生成其子类型的对象,使用dynamicType来实例化子类型对象,dynamicType代表动态类型,即其最顶层的子类类型。
假如此时ClazzA再派生一个子类ClazzB,使用copy方法来复制实例对象。可以先重载copyWithZone,然后再调用父类的copyWithZone来生成对象,最后对新复制的对象进行赋值,这点很重要,贴上代码一看就懂:
class ClazzB: ClazzA {
var memberB = 1
///重载copyWithZone
override func copyWithZone(zone: NSZone) -> AnyObject {
let theCopyObj = super.copyWithZone(zone) as! ClazzB
theCopyObj.memberB = self.memberB
return theCopyObj
}
}