WAKeyValuePersistenceStore 1.2

WAKeyValuePersistenceStore 1.2

测试已测试
Lang语言 Obj-CObjective C
许可 MIT
Released最近发布2016年2月

YuAo 维护。



  • 作者:
  • YuAo

WAKeyValuePersistenceStore 是一个简单基于文件的键值持久化存储库。

用法

创建 WAKeyValuePersistenceStore 很简单

self.store = WAKeyValuePersistenceStore(
        directory: NSSearchPathDirectory.CachesDirectory,
        name: "Store",
        objectSerializer: WAPersistenceObjectSerializer.keyedArchiveSerializer())

directory 是您想要存储数据文件的位置(缓存目录、文档目录、应用程序支持目录等)。

name 是存储库的名称。具有相同目录/名称组合的存储库共享相同的数据存储。

objectSerializer 控制对象被序列化的方式。

例如,WAPersistenceObjectSerializer.keyedArchiveSerializer() 使用 NSKeyedArchiverNSKeyedUnarchiver 来序列化和反序列化对象。

WAPersistenceObjectSerializer.passthroughSerializer() 用于直接将对象写入磁盘。您可能想要使用此对象序列化器来存储 NSData 对象。

您还可以创建自定义对象序列化器,方法是通过遵守 WAPersistenceObjectSerialization 协议。

使用下标存储或检索对象

var testData = NSProcessInfo.processInfo().globallyUniqueString
self.store["data"] = testData
//.....
var string = self.store["data"]

管理存储库或获取存储库的信息

//WAKeyValuePersistenceStore

//Get the store's path on disk.
var path: String { get }

//Get the preferred file URL for a key.
func fileURLForKey(key: String) -> NSURL

//Remove objects
func removeAllObjects()

func removeObjectsByLastAccessDate(date: NSDate, progressChangedBlock: ((UInt, UInt, UnsafeMutablePointer<ObjCBool>) -> Void)?)

//Store information
var currentDiskUsage: UInt { get }

var objectCount: UInt { get }

使用 Swift 的泛型

有为 WAKeyValuePersistenceStore 专门提供的 Swift 扩展。您可以在从存储库检索对象时指定对象类型。

extension WAKeyValuePersistenceStore {
    public func objectForKey<ValueType>(aKey: String, valueType: ValueType.Type) -> ValueType? {
        if let value = self.objectForKey(aKey) as? ValueType {
            return value
        } else {
            return nil
        }
    }
}

还有 WAKeyValuePersistenceStoreTypedAccessor<ValueType> 类。您可以使用它使用泛型来访问存储库。

例如

self.typedStore = WAKeyValuePersistenceStoreTypedAccessor<[Int]>(store: self.store)
var testData = [0,1,2,3,4,5,6]
self.typedStore["data"] = testData
//.....
var array = self.typedStore["data"] //array is [Int]

安装

您可以克隆仓库并手动添加 WAKeyValuePersistenceStore 目录中的文件

或者如果您使用 Cocoapods,请将以下内容添加到您的 Podfile 中

pod 'WAKeyValuePersistenceStore'

如果您使用 Swift,您可以通过添加以下内容来启用泛型支持

use_frameworks!

pod 'WAKeyValuePersistenceStore/Generics'

需求

  • 自动引用计数 (ARC)
  • iPhone 7.0+
  • Xcode 6.3+

贡献

如果您发现了一个错误并且确切知道如何修复它,请打开一个拉取请求。如果您无法自行进行更改,请在确认尚未记录问题后再打开一个问题。