Swift - 实现数组的深拷贝

关于数组深浅拷贝问题可参考 关于 strong,copy,深拷贝,浅拷贝 的整理 这篇文章,本文不再详述。在此仅列举一具体案例,并记录解决方式,以供参考。

 

json数据结构:

json=
{
  "data" : {
    "data" : [
      {
        "shop_id" : 1,
        "product_list" : [
          {
            "receive_time" : "75667",
            ......
          }
        ],
        "shop_name" : "xxxx"
      }
    ],
    "count" : 1
  },
  "code" : 0,
  "msg" : "成功"
}

 

模型结构:

// 接收json返回数据
class ProductCartListData : NSObject {    
    var data : [CartProductListModel]?    
}

// 商户列表の模型数组
class CartProductListModel : NSObject {    
    var productList : [ProductModel]?
    var shopId : Int?
    var shopName : String?
    var buyerNotes : String?    
}

// 商品Model
class ProductModel : NSObject, Mappable{
    var receiveTime : String?
	var receiveType : Int?
    ......
}

 

深拷贝方案:

每一级模型均需遵循 NSCopying, NSMutableCopying 协议,并在 copy(), mutableCopy() 方法中完成拷贝赋值。如下所示:

class ProductCartListData : NSObject, NSCopying, NSMutableCopying{    
    
    func copy(with zone: NSZone? = nil) -> Any {
        let dataModel = ProductCartListData.init()
        dataModel.data = self.data
        return dataModel
    }
    
    func mutableCopy(with zone: NSZone? = nil) -> Any {
        let dataModel = ProductCartListData.init()
        dataModel.data = self.data
        return dataModel
    }
    
}


class CartProductListModel : NSObject, NSCopying, NSMutableCopying{
        
    func copy(with zone: NSZone? = nil) -> Any {
        let listModel = CartProductListModel.init()
        listModel.productList = self.productList
        listModel.shopId = self.shopId
        listModel.shopName = self.shopName
        return listModel
    }
    
    func mutableCopy(with zone: NSZone? = nil) -> Any {
        let listModel = CartProductListModel.init()
        listModel.productList = self.productList
        listModel.shopId = self.shopId
        listModel.shopName = self.shopName
        return listModel
    }
    
}


extension ProductModel: NSCopying,NSMutableCopying {
    
    func copy(with zone: NSZone? = nil) -> Any {
        let pModel = ProductModel.init()
        pModel.receiveTime = self.receiveTime
        ......
        return pModel
    }
    
    func mutableCopy(with zone: NSZone? = nil) -> Any {
        let pModel = ProductModel.init()
        pModel.receiveTime = self.receiveTime
        ......
        return pModel
    }
}

在需要拷贝原数组时,直接使用相应的 copy 或 mutableCopy方法即可。详情如下:

    selModelArr = []
    
    // 深拷贝数组
    for listModel in cartListModelArr! {
        let copyListMdl: CartProductListModel = listModel.copy() as! CartProductListModel
        selModelArr.append(copyListMdl)
    }

 

 

参考文章:

关于 strong,copy,深拷贝,浅拷贝 的整理

如何在swift中实现数组的深拷贝

iOS 模型数组拷贝深度解析

Swift中如何深拷贝Array中的对象

 

你可能感兴趣的:(Swift - 实现数组的深拷贝)