What is the right way to present data from Realm in SwiftUI List

蓝咒 提交于 2021-02-05 07:00:34

问题


I’m trying to fetch all of the items from Realm and display them in a SwiftUI List but I keep getting an error.

In a UIKit/Realm application, I would just create a Results variable to store all of the items from Realm then, I would fetch items in the viewDidLoad method and assign them to the variable. I'm trying to do the same thing in SwiftUI but I'm not sure how to structure my code, I keep getting an error saying that my Realm model should conform to the StringProtocol, I'm pretty sure this has to do with my lack of understanding Binding in SwiftUI.

Again, all I’m trying to do is fetch all of the items from Realm and display them in a SwiftUI List.

Here is what I have.

Realm Object:

class User:Object{
    @objc dynamic var name:String = ""
    @objc dynamic var age:Int = 0
    @objc dynamic var createdAt = NSDate()

    @objc dynamic var userID = UUID().uuidString
    override static func primaryKey() -> String? {
        return "userID"
    }
}

SwiftUI Code:

struct ContentView: View {
    @State private var allUsers : Results<User>!
    var body: some View {
        VStack{
            List{
                ForEach(allUsers, id:\.self) { user in
                    Text(user) // the error points here
                }
            }
        }.onAppear(){
            self.updateUserResults()
        }
    }
    func updateUserResults(){
        allUsers = realm.objects(User.self)
    }
}

Error:

Initializer 'init(_:)' requires that 'User' conform to 'StringProtocol'

What am I missing?


回答1:


Probably you meant this

ForEach(allUsers, id:\.self) { user in
    Text(user.name)
}


来源:https://stackoverflow.com/questions/61160102/what-is-the-right-way-to-present-data-from-realm-in-swiftui-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!