gpt4 book ai didi

core-data - 使用 FetchRequest 时如何在 PreviewProvider 中显示示例数据

转载 作者:行者123 更新时间:2023-12-03 14:31:44 25 4
gpt4 key购买 nike

我有一个这样的 SwiftUI View :

import SwiftUI

struct ReView: View {
@Environment(\.managedObjectContext) var moc
@FetchRequest(
entity: Re.entity(),
sortDescriptors: [
NSSortDescriptor(keyPath: \Re.name, ascending: false)
]
) var entities: FetchedResults<Re>

var body: some View {
NavigationView {
List(entities, id: \.self) { entity in
Text(entity.name ?? "Unknown")
}
}
}
}

struct ReView_Previews: PreviewProvider {
static var previews: some View {
Group {

ReView()
.environment(\.managedObjectContext, PersistentCloudKitContainer.persistentContainer.viewContext)
}
}
}
如何在预览中显示一些示例数据?

最佳答案

这是经过调整的方法(早期在 https://stackoverflow.com/a/61495490/12299030 中提出),已使用 Xcode 12/iOS 14 进行测试
这个想法是将显式 View +模型与模型提供者(在这种情况下为云数据库)分开,因此可以设计和测试(预览)具有本地或动态构建的模拟模型(不涉及大量云连接)的 View

struct ReView: View {
@Environment(\.managedObjectContext) var moc
@FetchRequest(
entity: Re.entity(),
sortDescriptors: [
NSSortDescriptor(keyPath: \Re.name, ascending: false)
]
) var entities: FetchedResults<Re>

var body: some View {
ReEntitiesView(entities: entities)
}
}

struct ReEntitiesView<Results:RandomAccessCollection>: View where Results.Element == Re {
let entities: Results

var body: some View {
NavigationView {
List(entities, id: \.self) { entity in
Text(entity.name ?? "Unknown")
}
}
}
}

struct ReView_Previews: PreviewProvider {
static let entity = NSManagedObjectModel.mergedModel(from: nil)?.entitiesByName["Re"]

static var previews: some View {
let object = Re(entity: entity!, insertInto: nil)
object.name = "Test Name"

return ReEntitiesView(entities: [object])
}
}

关于core-data - 使用 FetchRequest 时如何在 PreviewProvider 中显示示例数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63230625/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com