0

These are my realm classes and functions:

class RealmItems: Object {
    @objc dynamic var header = String()
    @objc dynamic var specification = String()
    @objc dynamic var day = Int()
    @objc dynamic var month = Int()
    @objc dynamic var deadline = String()
    @objc dynamic var status = String()
}

class RealmModel {
    
    static let shared = RealmModel()
    private let realm = try! Realm()
    
    func addTask(headerTask: String, specificationTask: String, dayTask: Int, monthTask: Int, deadlineTask: String, statusTask: String) {
        
        let new = RealmItems()
        
        new.header = headerTask
        new.specification = specificationTask
        new.day = dayTask
        new.month = monthTask
        new.deadline = deadlineTask
        new.status = statusTask
        
        try! realm.write {
            realm.add(new)
        }
    }
    
    func deleteTask(name: RealmItems) {
        try! realm.write {
            realm.delete(name)
        }
    }
    
    func getTasks() -> [RealmItems] {
        
        var arrayTasks: [RealmItems] = []
        
        for task in realm.objects(RealmItems.self) {
            arrayTasks.append(task)
        }
        return arrayTasks.sorted{$0.day > $1.day}
    }    
}

function getTasks() doesn't work the way i want it works. Now collection shows oldest cells higher than newest - that's wrong. I want to newest were higher than oldest

vadian
  • 274,689
  • 30
  • 353
  • 361
  • Any serious database provides custom predicates to fetch data sorted. It's more efficient to use that. – vadian Jun 02 '21 at 17:54

1 Answers1

1

A few things to be aware of.

First, read Realm Objects Are Lazily Loaded e.g. don't cast them to an array or sort them using Swift functions. Well, you can but it can lead to other issues so best to avoid that unless there's a specific use case that requires it.

Secondly, Realm Results do not have a guaranteed order unless you specify that order. On the other hand, a List object maintains it's order.

Ordering a Results collection is simple, and actually keeps the objects in the results in order as object properties change, for example

let orderedResults = realm.objects(RealmItems.self).sorted(byKeyPath: "day", ascending: false)

Will load all of the RealmItems objects sorted by day, descending (e.g. 20th will be at the top and the 1st will be at the bottom)and the results will maintain their order. e.g. if a day changes, it will auto sort within the list. Pretty magical, huh?

Jay
  • 34,438
  • 18
  • 52
  • 81