Swift51.com
Swift 头像
Swift  2016-01-05 15:55

持久化类库Pantry

回复:0  查看:4886  感兴趣:9  赞:0  

可以持久化基础类型变量值的类库。

你可以存储以下类型

  • 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)
    }
}


相关开源代码