提问人:emirrou 提问时间:10/23/2023 最后编辑:emirrou 更新时间:10/24/2023 访问量:107
SwiftData 和 ValueTransformer 类似于核心数据
SwiftData with ValueTransformer similar to core data
问:
在核心数据中,您可以使用将单个属性转换为核心数据或从核心数据转换单个属性。这在存储/从托管上下文中获取某些属性时加密/解密某些属性等情况下非常有用。ValueTransformer
SwiftData 有类似的方法吗?我想加密保存我的数据,但在我的变量中解密它。@Query
我需要这个用于 iOS。
以下是使用核心数据的示例(图片来源:https://www.avanderlee.com/swift/valuetransformer-core-data/):ValueTransformer
override public func transformedValue(_ value: Any?) -> Any? {
guard let color = value as? UIColor else { return nil }
do {
let data = try NSKeyedArchiver.archivedData(withRootObject: color, requiringSecureCoding: true)
return data
} catch {
assertionFailure("Failed to transform `UIColor` to `Data`")
return nil
}
}
override public func reverseTransformedValue(_ value: Any?) -> Any? {
guard let data = value as? NSData else { return nil }
do {
let color = try NSKeyedUnarchiver.unarchivedObject(ofClass: UIColor.self, from: data as Data)
return color
} catch {
assertionFailure("Failed to transform `Data` to `UIColor`")
return nil
}
}
答:
2赞
emirrou
10/24/2023
#1
@joakim-danielson评论中的建议非常有效:)
从本质上讲,它是 Core Data 与 SwiftData 挂钩的。下面的示例在 和 之间进行转换。ValueTransformer
Date
String
这是 SwiftData 模型:Item
import Foundation
import SwiftData
@Model
final class Item {
@Attribute(.transformable(by: DateValueTransformer.name.rawValue))
var timestamp: Date
init(timestamp: Date) {
self.timestamp = timestamp
}
}
这是子类,它将日期保存为编码字符串:ValueTransformer
import Foundation
@objc(DateValueTransformer)
class DateValueTransformer: ValueTransformer {
var randomKey = "nothing"
private var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "YYYY-MM-dd HH:mm:ss"
return formatter
}()
override class func transformedValueClass() -> AnyClass {
return NSDate.self
}
override class func allowsReverseTransformation() -> Bool {
return true
}
override func transformedValue(_ value: Any?) -> Any? {
guard let date = value as? Date else { return nil }
let dateString = dateFormatter.string(from: date) + randomKey
print("transform: \(dateString)")
do {
return try NSKeyedArchiver.archivedData(withRootObject: dateString, requiringSecureCoding: true)
} catch {
assertionFailure("Failed to transform `Date` to `Data(String)`")
return nil
}
}
override func reverseTransformedValue(_ value: Any?) -> Any? {
guard let dateData = value as? Data else { return nil }
do {
guard let dateString = try NSKeyedUnarchiver.unarchivedObject(ofClass: NSString.self, from: dateData as Data) as? String
else { return nil }
print("reverse: \(dateString)")
return dateFormatter.date(from: String(dateString.dropLast(randomKey.count)))
} catch {
assertionFailure("Failed to transform `Data(String)` to `Date`")
return nil
}
}
}
extension DateValueTransformer {
static let name = NSValueTransformerName(rawValue: String(describing: DateValueTransformer.self))
public static func register(randomKey: String) {
let transformer = DateValueTransformer()
transformer.randomKey = randomKey
ValueTransformer.setValueTransformer(transformer, forName: name)
}
}
为了演示如何将动态值传递给 ,此代码段将 的实例注册到 自定义 :ValueTransformer
DateValueTransformer
randomKey
import SwiftUI
import SwiftData
@main
struct SwiftDataExperimentApp: App {
var sharedModelContainer: ModelContainer = {
DateValueTransformer.register(randomKey: "something")
let schema = Schema([
Item.self,
])
let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)
do {
return try ModelContainer(for: schema, configurations: [modelConfiguration])
} catch {
fatalError("Could not create ModelContainer: \(error)")
}
}()
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(sharedModelContainer)
}
}
通过 SwiftData 存储实例时,将获得以下控制台输出:Item
transform: 2023-10-23 09:56:53something
reverse: 2023-10-23 09:56:53something
这表明我们的习俗也在起作用。randomKey
评论
@Attribute(.transformable(by: <some transformer>)
ValueTransformer