Swift中自定義model的歸檔

首先對于歸檔的定義就不再贅述

最近在做一個項目,里面有一個功能是把購物車里的產品緩存到本地,由于數據量較少,選擇歸檔模式。

首先看一下數據模型。SSTCart對應的是購物車的model,里面包含兩個元素,一個是list數組,用來存放產品,一個是購物車所有產品的totalprice。list數組里面的的產品對應的model是SSTOrderItem

步驟一:對SSTCart的model進行encode

  • 遵從NSCoding協議
  • 實現coding協議
    required init?(coder aDecoder: NSCoder) {
    super.init()
    list = aDecoder.decodeObjectForKey("List") as! [SSTOrderItem]
    totalPrice = aDecoder.decodeDoubleForKey("TotalPrice")
    }
    override init() {
    }
    func encodeWithCoder(aCoder: NSCoder) {
    aCoder.encodeObject(list, forKey: "List")
    aCoder.encodeDouble(totalPrice, forKey: "TotalPrice")
    }

步驟二:對SSTOrderItem的model進行encode

  • 遵從NSCoding協議

  • 實現coding協議
    required init?(coder aDecoder: NSCoder) {
    super.init()
    cartId = aDecoder.decodeObjectForKey("CartId") as! NSNumber
    userId = aDecoder.decodeObjectForKey("UserId") as! NSNumber
    productId = aDecoder.decodeObjectForKey("ProductId") as! NSNumber
    unitPrice = aDecoder.decodeDoubleForKey("UnitPrice")
    createdate = aDecoder.decodeObjectForKey("Createdate") as! String
    qtyPrice = aDecoder.decodeDoubleForKey("QtyPrice")
    qty = aDecoder.decodeIntegerForKey("Qty")
    originUnitPrice = aDecoder.decodeDoubleForKey("OriginUnitPrice")
    imagePath = aDecoder.decodeObjectForKey("ImagePath") as! String
    productName = aDecoder.decodeObjectForKey("ProductName") as! String
    savedMoney = aDecoder.decodeDoubleForKey("SavedMoney")

    }
    override init() {
      
    }
    func encodeWithCoder(aCoder: NSCoder) {
      aCoder.encodeObject(cartId, forKey: "CartId")
      aCoder.encodeObject(userId, forKey: "UserId")
      aCoder.encodeObject(productId, forKey: "ProductId")
      aCoder.encodeDouble(unitPrice, forKey: "UnitPrice")
      aCoder.encodeObject(createdate, forKey: "Createdate")
      aCoder.encodeDouble(qtyPrice, forKey: "QtyPrice")
      aCoder.encodeInteger(qty, forKey: "Qty")
      aCoder.encodeDouble(originUnitPrice, forKey: "OriginUnitPrice")
      aCoder.encodeObject(imagePath, forKey: "ImagePath")
      aCoder.encodeObject(productName, forKey: "ProductName")
      aCoder.encodeDouble(savedMoney, forKey: "SavedMoney")
    }
    

這樣兩個model的encoding算是實現了

步驟三:歸檔和解檔的方法

自己寫了一個文件的讀寫的class
在這個class里面的代碼如下:
static func getFilePath(filePath: String) -> String? {

    var paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.AllDomainsMask, true)
    if paths.count > 0 {
        return "\(paths[0])/"+filePath
    }
    
    return nil
  }
    //MARK: 歸檔的方法
  static func archive(fileName: String, object: NSObject) -> Bool {
    let name = getFilePath(fileName)!
    return NSKeyedArchiver.archiveRootObject(object, toFile: name )
  }
  //MARK: 解檔的方法
  static func unarchive(fileName: String) -> AnyObject? {
    return NSKeyedUnarchiver.unarchiveObjectWithFile(getFilePath(fileName)!)
  }

步驟四:把請求得到的購物車數據進行歸檔

代碼如下:

    if FileOP.archive(kShoppingCartFileName, object: tmpSelf!.shoppingCart){
         print("add to file success")
     } else {
         print("add to file failure!")
     }             

其中,tmpSelf!.shoppingCart是從網絡請求之后得到的數據。

至此,歸檔操作已經完成,如果需要解檔操作的話,直接調用 unarchiver方法即可。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容