NSZone
在 Objective-C 中已经很久没有使用了。并且传递zone
的参数被忽略。从allocWithZone...
文档中引用:
这种方法的存在是出于历史原因;Objective-C 不再使用内存区域。
你也可以安全地忽略它。
这是一个如何符合NSCopying
协议的示例。
class GameModel: NSObject, NSCopying {
var someProperty: Int = 0
required override init() {
// This initializer must be required, because another
// initializer `init(_ model: GameModel)` is required
// too and we would like to instantiate `GameModel`
// with simple `GameModel()` as well.
}
required init(_ model: GameModel) {
// This initializer must be required unless `GameModel`
// class is `final`
someProperty = model.someProperty
}
func copyWithZone(zone: NSZone) -> AnyObject {
// This is the reason why `init(_ model: GameModel)`
// must be required, because `GameModel` is not `final`.
return self.dynamicType.init(self)
}
}
let model = GameModel()
model.someProperty = 10
let modelCopy = GameModel(model)
modelCopy.someProperty = 20
let anotherModelCopy = modelCopy.copy() as! GameModel
anotherModelCopy.someProperty = 30
print(model.someProperty) // 10
print(modelCopy.someProperty) // 20
print(anotherModelCopy.someProperty) // 30
PS 此示例适用于 Xcode 版本 7.0 beta 5 (7A176x)。特别是dynamicType.init(self)
.
为 Swift 3 编辑
以下是dynamicType
已弃用的 Swift 3 的 copyWithZone 方法实现:
func copy(with zone: NSZone? = nil) -> Any
{
return type(of:self).init(self)
}