如何在 SwiftUI 中使用 Realm [英] How to use Realm with SwiftUI
问题描述
我一直在研究如何在 SwiftUI 中使用 Realm.问题是 SwiftUI 和 Realm 都有一个 List 类型.当您将 SwiftUI 导入 Realm 模型以使类成为 BindableObject 并尝试创建 Realm List 属性时,会出现错误.
I have been trying to figure out how to use Realm with SwiftUI. The problem is that SwiftUI and Realm both have a List type. When you import SwiftUI into your Realm model to make the class a BindableObject and try to create a Realm List property there is an error.
是否可以使用 Realm 对象模型的实例并使其成为 SwiftUI 中的 BindableObject?
Is it possible to use an instance of the Realm object model and make it a BindableObject in SwiftUI?
推荐答案
当然,很简单,像这样使用模块标识符作为前缀:
Sure, it's very simple, use the module identifier as prefix like this :
let members = RealmSwift.List<Member>()
现在进入问题的第二部分.将 Realm 对象(或列表或结果集)封装在 BindableObject
中很容易:
Now to the second part of your question. It's easy to encapsulate a Realm object (or list, or resultset) in an BindableObject
:
final class DBData: BindableObject {
let didChange = PassthroughSubject<DBData, Never>()
private var notificationTokens: [NotificationToken] = []
var posts = Post.all
init() {
// Observe changes in the underlying model
self.notificationTokens.append(posts.observe { _ in
self.didChange.send(self)
})
self.notificationTokens.append(Message.all.observe { _ in
self.didChange.send(self)
})
}
}
如果您使用 @ObjectBinding
或 @EnvironmentObject
将 DBData
实例链接"到 SwiftUI View
> UI 将被刷新,并且 posts
的新值(在我们这里的示例中)将在每次基础领域发生变化时可用.
If you "link" a DBData
instance to a SwiftUI View
by either using @ObjectBinding
or @EnvironmentObject
the UI will be refreshed and the new value for posts
(in our example here) will be available each time the underlying realm changes.
这篇关于如何在 SwiftUI 中使用 Realm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!