Swift中自定义model的归档

作者: 小豆豆苗 | 来源:发表于2016-05-13 18:11 被阅读745次

首先对于归档的定义就不再赘述

最近在做一个项目,里面有一个功能是把购物车里的产品缓存到本地,由于数据量较少,选择归档模式。

首先看一下数据模型。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方法即可。

相关文章

网友评论

  • 廖马儿:in swift3:

    import UIKit

    class UserModel: NSObject,NSCoding {

    var username:String = ""
    var password: Int = 0

    required init(coder aDecoder: NSCoder) {
    super.init()

    }

    override init() {

    }

    func encode(with aCoder: NSCoder) {

    }

    }
  • 廖马儿:swift3 里面貌似改了,会报错: Type 'Usermodel' does not conform to protocal 'NSCoding'

本文标题:Swift中自定义model的归档

本文链接:https://www.haomeiwen.com/subject/btlmrttx.html