如何在Swift 2中符合NSCopying并实现copyWithZone? [英] How to conform to NSCopying and implement copyWithZone in Swift 2?
问题描述
我想在Swift 2中实现一个简单的GKGameModel
.Apple的示例在Objective-C中表达,并包含以下方法声明(GKGameModel
所继承的协议NSCopying
所要求的):
I would like to implement a simple GKGameModel
in Swift 2. Apple's example is expressed in Objective-C and includes this method declaration (as required by protocol NSCopying
from which GKGameModel
inherits):
- (id)copyWithZone:(NSZone *)zone {
AAPLBoard *copy = [[[self class] allocWithZone:zone] init];
[copy setGameModel:self];
return copy;
}
这如何转换为Swift 2?就效率和忽略区域而言,以下内容是否合适?
How does this translate into Swift 2? Is the following appropriate in terms of efficiency and ignoring zone?
func copyWithZone(zone: NSZone) -> AnyObject {
let copy = GameModel()
// ... copy properties
return copy
}
推荐答案
NSZone
长时间不在Objective-C中使用.并忽略传递的zone
参数.引用allocWithZone...
文档:
NSZone
is no longer used in Objective-C for a long time. And passed zone
argument is ignored. Quote from the allocWithZone...
docs:
此方法存在是出于历史原因;内存区域不再 由Objective-C使用.
This method exists for historical reasons; memory zones are no longer used by Objective-C.
您也可以忽略它.
这是一个如何符合NSCopying
协议的示例.
Here's an example how to conform to NSCopying
protocol.
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
P.S.本示例适用于Xcode 7.0 beta 5(7A176x).尤其是dynamicType.init(self)
.
P.S. This example is for Xcode Version 7.0 beta 5 (7A176x). Especially the dynamicType.init(self)
.
为Swift 3编辑
以下是由于不推荐使用dynamicType
的Swift 3的copyWithZone方法实现:
Below is the copyWithZone method implementation for Swift 3 as dynamicType
has been deprecated:
func copy(with zone: NSZone? = nil) -> Any
{
return type(of:self).init(self)
}
这篇关于如何在Swift 2中符合NSCopying并实现copyWithZone?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!