Filtering through large array causes freezing - Swift

不羁的心 提交于 2020-03-23 04:07:15

问题


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

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

I have also tried:

realm.objects(Thing.self).filter(NSPredicate("%@ IN kids", "Momo"))

But it does not work. I also tried to use SUBQUERY inside the predicate but it also does not work for primitive data types.

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.


回答1:


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

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

Hope this helps



来源:https://stackoverflow.com/questions/60674146/filtering-through-large-array-causes-freezing-swift

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