Sort Realm Objects with List Property Count

I have two classes of Realm data models:

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 the number of tasks in each of them. I tried using something like this, but it disables the application because it is not supported:

realm.objects(TaskList).sorted("tasks.count")
+4
source share
2 answers

Like this:

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

EDIT: I have no idea about Realm, it only works when it objectsreturns CollectionTypeand Listhas a property count.

+3
source

Another workaround is:

Enter the property taskCountin TaskListand always synchronize taskCountand 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")

Realm , .

taskCount tasks.count, :

( tasks.append() , addTask().)

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()
        }
    }
}
+3

Source: https://habr.com/ru/post/1613028/


All Articles