简体   繁体   中英

Sort Realm objects with the count of List property

I have two Realm data models classes like this:

class TaskList: Object {

   dynamic var name = ""
   dynamic var createdAt = NSDate()
   let tasks = List<Task>()
}

And:

class Task: Object {

   dynamic var name = ""
   dynamic var createdAt = NSDate()
   dynamic var notes = ""
   dynamic var isCompleted = false
}

Now I need to query TaskList and sort them with number of tasks in each of them. I tried to use something like this but it crashes the app because its not supported:

realm.objects(TaskList).sorted("tasks.count")

Another workaround is:

Introduce taskCount property in TaskList , and make always sync taskCount and tasks.count .

class TaskList: Object {
    dynamic var name = ""
    dynamic var createdAt = NSDate()
    let tasks = List<Task>()
    dynamic var taskCount = 0
}

Then, you can use

realm.objects(TaskList).sorted("taskCount")

Since Realm does not support sorting on key paths, currently.

If you'd like to sync taskCount and tasks.count automatically, you can do like the following:

(Don't use tasks.append() directly, use addTask() method instead.)

class TaskList: Object {
    dynamic var name = ""
    dynamic var createdAt = NSDate()
    private let tasks = List<Task>()
    dynamic var taskCount = 0

    func addTask(task: Task) {
        func add() {
            tasks.append(task)
            taskCount = tasks.count
        }
        if let realm = realm where !realm.inWriteTransaction {
            try! realm.write{
                add()
            }
        } else {
            add()
        }
    }
}

Like this:

realm.objects(TaskList).sort { $0.tasks.count < $1.tasks.count }

EDIT: have no idea about Realm, this only works when objects returns a CollectionType and List has a count property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM