WAKeyValuePersistenceStore
是一个简单基于文件的键值持久化存储库。
创建 WAKeyValuePersistenceStore
很简单
self.store = WAKeyValuePersistenceStore(
directory: NSSearchPathDirectory.CachesDirectory,
name: "Store",
objectSerializer: WAPersistenceObjectSerializer.keyedArchiveSerializer())
directory
是您想要存储数据文件的位置(缓存目录、文档目录、应用程序支持目录等)。
name
是存储库的名称。具有相同目录/名称组合的存储库共享相同的数据存储。
objectSerializer
控制对象被序列化的方式。
例如,WAPersistenceObjectSerializer.keyedArchiveSerializer()
使用 NSKeyedArchiver
和 NSKeyedUnarchiver
来序列化和反序列化对象。
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'
如果您发现了一个错误并且确切知道如何修复它,请打开一个拉取请求。如果您无法自行进行更改,请在确认尚未记录问题后再打开一个问题。