我试图在SwiftUI列表中显示realmdb查询的结果,但在删除数据库对象时遇到问题。
我正在尝试使用这样的东西:
final class DBData: ObservableObject{
let didChange = PassthroughSubject<DBData, Never>()
private var notificationTokens: [NotificationToken] = []
var events = try! Realm().objects(ADMEvent.self)
@Published var events: [ADMEvent] = []
init() {
// Observe changes in the underlying model
self.notificationTokens.append(posts.observe { _ in
self.events = Array(self.posts)
self.didChange.send(self)
})
}
}
如果我在列表中显示项目,但当我使用realm.deleteAll((时,应用程序崩溃,因为看起来Swift UI的列表实现正在尝试区分列表,访问现在无效的realm-db对象。
关于堆栈溢出,有3到4个类似的问题,但它们都以某种方式过时了,或者有效,但在删除时仍然存在这个问题。
谢谢!
Realm对象是实时自动更新的,这就是为什么当你试图抓住已删除的对象时,它们会崩溃。而不是给你的出版主题领域。对象将其映射到一个只有您需要使用的字段的结构,并使用该数组来驱动SwiftUI。
struct Event: Identifiable {
var id: String
var name: String
var date: Date
}
final class DBData: ObservableObject {
private var notificationTokens: [NotificationToken] = []
var events = try! Realm().objects(ADMEvent.self)
@Published var publishedEvents: [ADMEvent] = []
init() {
// Observe changes in the underlying model
self.notificationTokens.append(posts.observe { _ in
self.publishedEvents = events.map { Event(id: $0.id, name: $0.name, date: $0.date)}
})
}
}
我喜欢这种方法!我只想把这个放在那里,因为公认的答案不会编译,而且有不止一个问题:
@Published var publishedEvents: [ADMEvent] = []
应该是:
@Published var publishedEvents: [Event] = []
和
self.notificationTokens.append(posts.observe { _ in
应该是:
self.notificationTokens.append(events.observe { _ in
所以
final class DBData: ObservableObject {
private var notificationTokens: [NotificationToken] = []
var events = try! Realm().objects(ADMEvent.self)
@Published var publishedEvents: [Event] = []
init() {
// Observe changes in the underlying model
self.notificationTokens.append(events.observe { _ in
self.publishedEvents = events.map { Event(id: $0.id, name: $0.name, date: $0.date)}
})
}
}