How to query List<Int> on Realm Swift

久未见 提交于 2019-12-11 17:42:46

问题


How can I filter out the RealmFilter.objectIds that has a given Int?

func delete(ids: [Int]) {
   let filterResultsToDelete = realm.objects(CRMRealmFilterResult.self).filter("ANY objectIds IN %@",ids)
//Crashes
}


class RealmFilterResult : Object {
    @objc dynamic var filterId: Int = 0
    let objectIds = List<Int>()

    override static func primaryKey() -> String {
        return "filterId"
    }
  }

回答1:


This may not be at all what you want but it was a good exercise. Maybe this will help.

Let me re-state what I think you're asking: You've got a series of objects that each have a List property of Int's and you want to be able to query for all objects that have a particular int in their list

Using a more real-world example, suppose we have a list of teams and we keep a list of game scores (a list) within each team

class TeamObject: Object {
    @objc dynamic var object_id = NSUUID().uuidString

    let scoreList = List<ScoreObject>()

    override static func primaryKey() -> String? {
        return "object_id"
    }
}

and we have a score object that stores a score as an Int (and maybe other details like who they played or the date)

class ScoreObject: Object {
    @objc dynamic var score = 0
    let teamsWithScores = LinkingObjects(fromType: TeamObject.self, property: "scoreList")
}

For simplicity, let's create three scores and two teams and give each team two scores in their list.

let score1 = ScoreObject()
score1.score = 1
let score2 = ScoreObject()
score2.score = 2
let score3 = ScoreObject()
score3.score = 3

let t1 = TeamObject()
t1.scoreList.append(score1)
t1.scoreList.append(score3)

let t2 = TeamObject()
t2.scoreList.append(score2)
t2.scoreList.append(score3)

and write them to realm

try! realm.write {
    realm.add(t1)
    realm.add(t2)
}

from there, we can get any team that has a score of 1, which solves the question of getting the objects that have a list that contain a given int.

let results = realm.objects(ScoreObject.self).filter("score IN %@", [1])
if results.count > 0 {
    for aScore in results {
        let teamsWithThisScore = aScore.teamsWithScores
        for team in teamsWithThisScore {
            print("score: \(aScore.score)")
            print("     id: \(team.object_id)")
        }
    }
} else {
    print("no teams with those scores")
}

you can expand on this to get teams (object) that have several scores (ints)

let results = realm.objects(ScoreObject.self).filter("score IN %@", [1,3])

As I said, it may be off base but it does provide a solution in a more object oriented way.




回答2:


Querying List of primitives (i.e. non Object subclasses, like Int in your case) is not yet supported by Realm.

You can follow the status of this on this GitHub issue.



来源:https://stackoverflow.com/questions/54133305/how-to-query-listint-on-realm-swift

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