如何在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屋!