【问题标题】:how to clone object model swift如何快速克隆对象模型
【发布时间】:2018-12-03 04:21:50
【问题描述】:

我想使用Mirror添加到父类,而不必添加子类的克隆

你认为这可能吗?

基类:

class BaseModel {

 func clone() -> BaseModel {

          let mirror = Mirror(reflection : self)
           for (lable , value) in mirror.children {

             }
          return ...
   }
}

子类:

class UserModel:BaseModel {

   var name:String!
   var family:String!

}

用法:

 let cloneModel = self.userModel.clone()

【问题讨论】:

  • 不需要这样做,因为您可以在 swift 中创建对象的副本。只需使用结构创建模型,然后将其分配给新变量,自动创建分配的新副本模型到新变量。
  • Y_Y thamks,项目我不能改变模型的结构

标签: ios swift reflection prototype mirror


【解决方案1】:

你必须实现NSCopying协议并覆盖copy(with:)函数:

class BaseModel: NSCopying {

   var xx: String?
   var yy: Int?

   private init(xx: String, yy: Int) {
       self.xx = xx
       self.yy = yy
   }

   func copy(with zone: NSZone? = nil) -> Any {
       let copy = BaseModel(xx: xx, yy: yy)
       return copy
   }
}

用法:

let clone = model.copy() as! BaseModel

或者你可以参考这个答案: https://stackoverflow.com/a/32113575/3882414

【讨论】:

  • 谢谢,但我想要 UserModel,克隆子模型类而不是父类
  • 同理,让子类符合NSCopying协议并覆盖copy(with:)函数
猜你喜欢
  • 1970-01-01
  • 2012-07-25
  • 2010-11-08
  • 2012-11-17
  • 2010-09-07
  • 2012-12-07
  • 1970-01-01
  • 1970-01-01
  • 2011-11-07
相关资源
最近更新 更多