如何快速克隆对象模型

时间:2018-06-24 10:41:24

标签: ios swift reflection prototype mirror

我想使用 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()

1 个答案:

答案 0 :(得分:0)

您必须实现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