Chcel by som implementovať jednoduchý GKGameModel
v Swift 2. Príklad Apple je vyjadrený v Objective-C a obsahuje túto deklaráciu metódy (ako to vyžaduje protokol) NSCopying
z ktorých GKGameModel
dedí):
- (id)copyWithZone:(NSZone *)zone {
AAPLBoard *copy = [[[self class] allocWithZone:zone] init];
[copy setGameModel:self];
return copy;
}
Ako sa to premieta do Swift 2? Je nasledujúce z hľadiska účinnosti a ignorovania zóny vhodné?
func copyWithZone(zone: NSZone) -> AnyObject {
let copy = GameModel()
// ... copy properties
return copy
}
odpovede:
32 pre odpoveď č. 1NSZone
sa už dlho nepoužíva v Objective-C. A prešiel zone
argument sa ignoruje. Citát z allocWithZone...
docs:
Táto metóda existuje z historických dôvodov; pamäťové zóny už nie sú používa Objective-C.
Môžete to tiež bezpečne ignorovať.
Tu je príklad, ako sa prispôsobiť NSCopying
protokol.
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: Tento príklad sa týka Xcode verzie 7.0 beta 5 (7A176x). Najmä dynamicType.init(self)
.
Upraviť pre Swift 3
Nižšie je uvedená implementácia metódy copyWithZone pre Swift 3 as dynamicType
bol zastaraný:
func copy(with zone: NSZone? = nil) -> Any
{
return type(of:self).init(self)
}