Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")
like image 470
Hossam Ghareeb Avatar asked Oct 24 '15 16:10

Hossam Ghareeb


2 Answers

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 image 192
kishikawa katsumi Avatar answered Nov 15 '22 06:11

kishikawa katsumi


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.

like image 24
Kametrixom Avatar answered Nov 15 '22 06:11

Kametrixom