歡迎加入QQ討論群258996829

持久化類庫Pantry

發(fā)布時間:2016-01-05 15:55  回復:0  查看:5105  感興趣:9  贊:0   最后回復:2016-01-05 15:55  

可以持久化基礎類型變量值的類庫。

你可以存儲以下類型

  • Structs
  • Strings, Ints and Floats (our default types)
  • Arrays of structs and default types
  • Nested structs
  • Classes
  • Arrays of classes and default types
  • Nested classes

基礎類型(String, Int, Float, Bool)

if let available: Bool = Pantry.unpack("promptAvailable") {
    completion(available: available)
} else {
    anExpensiveOperationToDetermineAvailability({ (available) -> () in
      Pantry.pack(available, key: "promptAvailable", expires: .Seconds(60 * 10))
      completion(available: available)
    })
}
自動的持久化變量
使用Swift的get/set自動持久化一個變量的值,改變值后可讀取最新的值。
var autopersist: String? {
    set {
        if let newValue = newValue {
            Pantry.pack(newValue, key: "autopersist")
        }
    }
    get {
        return Pantry.unpack("autopersist")
    }
}

...later...

autopersist = "Hello!"
// restart app, reboot phone, etc
print(autopersist) // Hello!
結構體
struct Basic: Storable {
    let name: String
    let age: Float
    let number: Int

    init(warehouse: JSONWarehouse) {
        self.name = warehouse.get("name") ?? "default"
        self.age = warehouse.get("age") ?? 20.5
        self.number = warehouse.get("number") ?? 10
    }
}
class ModelBase: Storable {
    let id: String

    required init(warehouse: Warehouseable) {
        self.id = warehouse.get("id") ?? "default_id"
    }
}

class BasicClassModel: ModelBase {
    let name: String
    let age: Float
    let number: Int

    required init(warehouse: Warehouseable) {
        self.name = warehouse.get("name") ?? "default"
        self.age = warehouse.get("age") ?? 20.5
        self.number = warehouse.get("number") ?? 10

        super.init(warehouse: warehouse)
    }
}


相關開源代碼

您還未登錄,請先登錄

熱門帖子

最新帖子

?