Herczeg Ádám
Herczeg Ádám

Reputation: 203

Convert from Realm Results to Array produce empty objects

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.

Upvotes: 2

Views: 4064

Answers (2)

Shohei Fukui
Shohei Fukui

Reputation: 1

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 = ""
}

Upvotes: 0

Nixsm
Nixsm

Reputation: 37

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

Upvotes: 2

Related Questions