一个基于Swift的轻量级框架,可实现Swift属性在预配置的存储上的持久化。
目录
特性亮点
- 兼容iOS、macOS、watchOS和tvOS
- 原生支持基于
UserDefaults
的存储 - 原生支持基于iOS
KeyChain
的存储 - 通过
@Persisted
属性包装器实现属性持久化 - 使用
@Persisted
包装的属性必须符合Codable
协议 - 可以指定您自定义的存储设施
基本用法
创建持久化属性只需在您的变量上添加 @Persisted
属性包装器,指定用于在存储中反射属性值的键,并为属性本身分配一个默认值。如果属性是 Optional
且未提供默认值,则必须指定 nil
。
@Persisted(key: "myProperty")
var myProperty: Double = 10.0
@Persisted(key: "myOptionalProperty")
var myOptionalProperty: String? = nil // default value cannot be omitted
高级使用
可以自定义在哪种存储服务上持久化属性。`PersistedProperty`提供了对基于`UserDefaults`的存储和基于`KeyChain`的存储的原生支持。你可以在你属性的`@Persisted`属性包装器上配置使用哪种存储。
// This will be persisted in the standard UserDefaults (same as omitting the storage parameter).
@Persisted(key: "myProperty", storage: .standard)
var myProperty: Double = 10.0
// This will be persisted in the iOS KeyChain.
@Persisted(key: "myPassword", storage: .keychain)
var myPassword: String? = nil
此外,你可以通过创建符合`StorageService`协议的存储提供者来指定你的自定义存储服务。
/// A custom storage provider conforming to the StorageService protocol
class MyCustomStorageService: StorageService {
func load<ValueType>(key: String) -> ValueType? where ValueType: Codable ...
func save<ValueType>(_ value: ValueType, key: String) where ValueType: Codable ...
func remove(key: String) ...
}
let myService: StorageService = MyCustomStorageService()
// This will be persisted in the custom storage service.
@Persisted(key: "myProperty", storage: .custom(service: myService))
var myProperty: Double = 10.0
安装
Cocoapods
将`PersistedProperty`框架的依赖关系添加到你的`Podfile`中。
pod 'PersistedProperty', '~> 1.1.0'
Swift Package Manager
将其作为依赖项添加到Swift Package。
dependencies: [
.package(url: "https://github.com/danielepantaleone/PersistedProperty.git", .upToNextMajor(from: "1.1.0"))
]
贡献
如果您喜欢这个项目,您可以通过以下方式为其做出贡献:
许可协议
MIT License
Copyright (c) 2023 Daniele Pantaleone
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.