LocalStorage
示例
要运行示例项目,克隆存储库并在 Xcode 11+ 中打开 Example/Example.xcodproj。
1. 选择一个要持久化的模型
/// Make model Codable to use default Decoder and Encoder
struct User: Codable {
let name: String
init(name: String) {
self.name = name
}
}
2. 创建 LocalStorage.Manager 实例并注册存储
// Identifies existing Storages. Used internally for easy storage access through LocalStorage.Manager.
enum Identifier: String {
case user
// Path to store data to.
var path: String {
switch self {
case .user: return "example.storage.user"
}
}
}
// Storage persisting data to user storage to key 'path'
let defaultsStorage = UserDefaultsStorage(userDefaults: UserDefaults.standard, path: Identifier.user.path)
// Wrap defaultsStorage with CachedStorage for faster access.
let userStorage = CachedStorage(storage: defaultsStorage)
// Dictionary containing all storages handled by Manager instance
let storages = [Identifier.user.rawValue: userStorage]
// DispatchLock to allow multiple reads but single write operations on storages. It will perform all
// operations on a concurrent DispatchQueue. It is also possible to simply use a NSLock, which may be
// easier to handle due to reduced thread states. On the downside NSLock has a lower performance on read
// operations than a DispatchLock.
let lock = DispatchLock(queue: DispatchQueue(label: "example.queue.storage", attributes: .concurrent))
// Serial queue for async handling. Enables sequential dispatching of completion blocks.
// Needed for required behaviour in example app.
// NOTE: Default Manager(storages: _, lock: _) uses a concurrent queue.
let asyncQueue = DispatchQueue(label: "async.queue")
let manager = Manager(storages: storages, lock: lock, asyncQueue: asyncQueue)
3. 保存用户
let user = User(name: "Bernd")
let encoder = FoundationEncoder<User>(encoder: JSONEncoder())
// Prefer async access over sync access
// Sync access := manager.append(_, using: _) -> Result<T, Error>
manager.async.append(user, to: Identifier.user.rawValue, using: encoder) { result in
switch result {
case .success(let savedUser):
print("\(savedUser.name)")
case .failure(let error):
print(error)
}
}
4. 加载存储的用户列表
let decoder = FoundationDecoder<User>(decoder: JSONDecoder())
// Prefer async access over sync access
// Sync access := manager.all(from: _, using: _) -> Result<[T], Error>
manager.async.all(from: Identifier.user.rawValue, using: decoder) { result in
switch result {
case .success(let user):
user.forEach { print("\($0.name)") }
case .failure(let error):
print(error)
}
}
需求
- Swift 5.0+
- iOS 11.0+
- tvOS 11.0+
- watchOS 5.0+
安装
Swift Package Manager
dependencies: [
.package(url: "https://github.com/cellular/cellular-swift.git", from: "6.0.0")
]
CocoaPods
pod "CellularLocalStorage"
许可协议
CellularLocalStorage遵循MIT许可协议。有关详细信息请参阅LICENSE。