Hossam Ghareeb Hossam Ghareeb - 6 months ago 27
iOS Question

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")

Answer

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.