从Realm Results转换为Array会产生空对象 [英] Convert from Realm Results to Array produce empty objects

查看:106
本文介绍了从Realm Results转换为Array会产生空对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试从结果转换为Swift数组时,属性位于默认值上.

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

因此,假设我编写了这样的Request对象:

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

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

然后当我像这样从Realm中阅读它们时:

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

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

我得到的结果很好.我需要将Results对象转换为Array.我做到了:

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

let requests = Array(requestsFromRealm)

请求对象在那里,但是属性在默认值上.奇怪的是,当我用po检查控制台上的值时,我可以看到它们.

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.

推荐答案

尝试一下:

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

使用此扩展程序:

extension Results {

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

这篇关于从Realm Results转换为Array会产生空对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆