如何符合NSCopying并在Swift 2中实现copyWithZone?

前端之家收集整理的这篇文章主要介绍了如何符合NSCopying并在Swift 2中实现copyWithZone?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在 Swift 2中实现一个简单的GKGameModel.苹果的例子在Objective-C中表达,并包含这个方法声明(根据GKGameModel继承的NSCopying协议的要求):
  1. - (id)copyWithZone:(NSZone *)zone {
  2. AAPLBoard *copy = [[[self class] allocWithZone:zone] init];
  3. [copy setGameModel:self];
  4. return copy;
  5. }

这怎么翻译成Swift 2?在效率和忽视区方面是否适合?

  1. func copyWithZone(zone: NSZone) -> AnyObject {
  2. let copy = GameModel()
  3. // ... copy properties
  4. return copy
  5. }
NSZone已经不再在Objective-C中使用了很长时间.而传递的区域参数被忽略.从allocWithZone引用… docs:

This method exists for historical reasons; memory zones are no longer
used by Objective-C.

你也可以忽略它.

下面是一个如何符合NSCopying协议的例子.

  1. class GameModel: NSObject,NSCopying {
  2.  
  3. var someProperty: Int = 0
  4.  
  5. required override init() {
  6. // This initializer must be required,because another
  7. // initializer `init(_ model: GameModel)` is required
  8. // too and we would like to instantiate `GameModel`
  9. // with simple `GameModel()` as well.
  10. }
  11.  
  12. required init(_ model: GameModel) {
  13. // This initializer must be required unless `GameModel`
  14. // class is `final`
  15. someProperty = model.someProperty
  16. }
  17.  
  18. func copyWithZone(zone: NSZone) -> AnyObject {
  19. // This is the reason why `init(_ model: GameModel)`
  20. // must be required,because `GameModel` is not `final`.
  21. return self.dynamicType.init(self)
  22. }
  23.  
  24. }
  25.  
  26. let model = GameModel()
  27. model.someProperty = 10
  28.  
  29. let modelCopy = GameModel(model)
  30. modelCopy.someProperty = 20
  31.  
  32. let anotherModelCopy = modelCopy.copy() as! GameModel
  33. anotherModelCopy.someProperty = 30
  34.  
  35. print(model.someProperty) // 10
  36. print(modelCopy.someProperty) // 20
  37. print(anotherModelCopy.someProperty) // 30

附:此示例适用于Xcode Version 7.0 beta 5(7A176x).特别是dynamicType.init(self).

为Swift 3编辑

以下是Swift 3的copyWithZone方法实现,因为dynamicType已被弃用:

  1. func copy(with zone: NSZone? = nil) -> Any
  2. {
  3. return type(of:self).init(self)
  4. }

猜你在找的Swift相关文章