How to use Realm with SwiftUI

后端 未结 2 1282
没有蜡笔的小新
没有蜡笔的小新 2020-12-13 16:53

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

2条回答
  •  情深已故
    2020-12-13 17:03

    Sure, it's very simple, use the module identifier as prefix like this :

    let members = RealmSwift.List()
    

    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()
    
        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)
            })
        }
    }
    

    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.

提交回复
热议问题