对象深拷贝

背景:
在不希望更改传入数据源的情况下,可以通过深拷贝的情况,创建一个新的数据源。
(1)方法 1:
深拷贝对象的类文件需要遵守 NSCopying 协议,重写 copy(with zone: NSZone? = nil) 方法,并且将属性一一赋值。
(2)方法 2:
直接创建一个新的model(结合HandyJson)

方法一:

  1. GroupLevelListModel.swift文件
import UIKit

class GroupLevelListModel: BaseModel,NSCopying {
    
    func copy(with zone: NSZone? = nil) -> Any {
        let model = GroupLevelListModel()
        model.level = level
        model.student_list = [GroupLevelStudentListModel]()
        for stu in student_list {
            let newStu = stu.copy() as! GroupLevelStudentListModel
            model.student_list.append(newStu)
        }
        return model
    }
    
    var level: String?
    var student_list = [GroupLevelStudentListModel]()

}
  1. GroupLevelStudentListModel.swift文件:
import UIKit

class GroupLevelStudentListModel: BaseModel,NSCopying {

    func copy(with zone: NSZone? = nil) -> Any {
        let model = GroupLevelStudentListModel()
        model.name = name
        model.portrait = portrait
        model.student_username = student_username
        model.exist_group = exist_group
        model.isSelected = isSelected
        return model
    }
    
    var name: String?
    var portrait: String?
    var student_username: String?
    var exist_group: String?
    var isSelected = false
}

方法二:

//copy对象,不能直接指向这个对象
let model = JSONDeserializer.deserializeFrom(dict: model?.toJSON() as NSDictionary?)

你可能感兴趣的:(对象深拷贝)