通过大数组过滤会导致冻结-Swift [英] Filtering through large array causes freezing - Swift
问题描述
我正在尝试过滤具有字符串数组的大型对象数据库,在这种情况下为kids
.
I'm trying to filter through a large database of objects with arrays of strings, in this case, kids
.
class Thing: Object, Decodable {
@objc dynamic var id: String?
let kids = List<String>
}
由于Realm不支持查询数组中的原始数据(根据Realm,您尚不能使用谓词和过滤器来执行此操作),因此我正在使用它来对它们进行过滤:
Since Realm does not support querying primitive data in arrays (According to Realm, you can't use a predicate & filter to do this yet), I'm using this to filter through them:
let things = realm.objects(Thing.self)
for thing in things {
if thing.kids.contains("Momo") {
// Success
}
}
我也尝试过:
realm.objects(Thing.self).filter(NSPredicate("%@ IN kids", "Momo"))
但是它不起作用.我还尝试在谓词中使用SUBQUERY
,但它也不适用于原始数据类型.
But it does not work. I also tried to use SUBQUERY
inside the predicate but it also does not work for primitive data types.
因为我有成千上万个Thing
对象,所以这非常慢,并且冻结了我的应用程序.有没有一种方法可以加快速度,或者至少不冻结我的应用程序?我无法为字符串创建新的自定义类,因为必须完全更改存储所有内容的JSON.
Because I have thousands of Thing
objects, this is very slow and it freezes my app. Is there a way to speed this up or make it not freeze my app at least? I can't make a new custom class for strings because I would have to completely change my JSON, which is where everything is stored.
推荐答案
基于注释,您可以尝试在后台线程中执行任务.不过,对UI的更新必须使用主线程.
Based on comments, you can try executing the task in a background thread. Updates to the UI must use the main thread though.
DispatchQueue.global(qos: .background).async
在下面的块中移动冻结UI的代码,以使其异步执行.
Move the code that freezes your UI in the below block to get it executed asynchronously.
DispatchQueue.main.async(execute: {
// Place code that freezes UI or takes time to execute here.
let things = realm.objects(Thing.self)
for thing in things {
if thing.kids.contains("Momo") {
// Success
}
}
}
希望这会有所帮助
这篇关于通过大数组过滤会导致冻结-Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!