加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 05:19:47 所属栏目:百科 来源:网络整理
导读:我想在 Swift 2中实现一个简单的GKGameModel.苹果的例子在Objective-C中表达,并包含这个方法声明(根据GKGameModel继承的NSCopying协议的要求): - (id)copyWithZone:(NSZone *)zone { AAPLBoard *copy = [[[self class] allocWithZone:zone] init]; [copy se
我想在 Swift 2中实现一个简单的GKGameModel.苹果的例子在Objective-C中表达,并包含这个方法声明(根据GKGameModel继承的NSCopying协议的要求):
- (id)copyWithZone:(NSZone *)zone {
    AAPLBoard *copy = [[[self class] allocWithZone:zone] init];
    [copy setGameModel:self];
    return copy;
}

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

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

This method exists for historical reasons; memory zones are no longer
used by 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

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

为Swift 3编辑

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读