Convert from Realm Results to Array produce empty objects

心不动则不痛 提交于 2019-12-08 01:38:44

问题


When I try to convert from Results to Swift Array the properties are on the default values.

So let's say I write a Request object like this:

let realm = try! Realm()
try! realm.write {
    realm.add(request, update: true)
}

Then when I'm reading them from Realm like this:

 let realm = try! Realm()
 let requestsFromRealm = realm.objects(Request.self)

I got the results just fine. I need to convert the Results object to Array. I did it:

let requests = Array(requestsFromRealm)

The requests objects are there, but the properties are on the default values. The weird thing is, when I check the values on the console with po I can see them.


回答1:


Try this:

let realm = try! Realm()
let requestsFromRealm = realm.objects(Request.self)
let requests = requestsFromRealm.toArray()

Using this extension:

extension Results {

    func toArray() -> [T] {
        var array = [T]()
        for result in self {
            array.append(result)
        }
        return array
    }
}



回答2:


let requests = Array (requestsFromRealm)

I think that there is no problem with this code.

Is not "dynamic" missing in the property of Realm Object?

class Request: Object {
     dynamic var body: String = ""
}


来源:https://stackoverflow.com/questions/43786859/convert-from-realm-results-to-array-produce-empty-objects

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