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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With