我在尝试使用带有预览的内存领域配置时遇到了问题。当预览执行时,它会返回一个错误。诊断给出以下错误:
消息错误:连接中断
我定义了以下类来模拟领域数据。
class MockRealms {
static var previewRealm: Realm {
get {
var realm: Realm
let identifier = "previewRealm"
let config = Realm.Configuration(inMemoryIdentifier: identifier)
do {
realm = try Realm(configuration: config)
try realm.write {
for category in Categories.allCases {
_ = Category(name: category.rawValue)
}
}
try realm.write {
_ = Settings(type: .fixed, int: 3.375, dp: 25.0, term: 30)
}
return realm
} catch let error {
fatalError("Error: \(error.localizedDescription)")
}
}
}
}
在视图中,我们使用@ObservedResults 从领域中获取类别。
struct PropertyListView: View {
@ObservedResults(Category.self) var categories
@Binding var showInfo: Bool
@Binding var showInfoButton: Bool
@Binding var showGuide: Bool
@Binding var showGuideButtton: Bool
var body: some View {
NavigationView {
ScrollView {
VStack {
ForEach(categories) { category in
PropertyCategoryView(category: category)
}
}
}
}
.navigationBarTitle("Property List")
.navigationBarBackButtonHidden(false)
}
.navigationViewStyle(.stack)
}
预览部分如下:
struct PropertyListView_Previews: PreviewProvider {
static var previews: some View {
Group {
PropertyListView(showInfo: .constant(false), showInfoButton:
.constant(true), showGuide: .constant(false), showGuideButton:
.constant(false))
.environment(\.realm, MockRealms.previewRealm)
PropertyListView(showInfo: .constant(false), showInfoButton:
.constant(true), showGuide: .constant(false), showGuideButton:
.constant(false))
.environment(\.realm, MockRealms.previewRealm)
.preferredColorScheme(.dark)
}
}
}
非常感激任何的帮助。