Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort Results in Realm

Tags:

swift

realm

I am using Realm with Swift. I want to sort "pictures" saved in Realm by PhotoCollectionViewController in the reverse order of date. I don't know what should I do. I would be pleased if you could lend me your wisdom.

Models.swift

import RealmSwift

class Entry: Object {
    @objc dynamic var text = ""
    @objc dynamic var date = Date()
    let pictures = List<Picture>()
    }
class Picture: Object {
    @objc dynamic var fullImageName = ""
    @objc dynamic var thumbnailName = ""
    @objc dynamic var entry : Entry?
    }

PhotoCollectionViewController.swift

import UIKit
import RealmSwift

class PhotoCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    var pictures : Results<Picture>?

    override func viewWillAppear(_ animated: Bool) {
        getPictures()
    }

    func getPictures() {
        if let realm = try? Realm() {
            pictures = realm.objects(Picture.self)
            //I want to sort pictures in the reverse order of date
            collectionView?.reloadData()
        }
    }
…
}
like image 426
sayaka Avatar asked Mar 05 '23 17:03

sayaka


1 Answers

You should be able to sort it with the following code

realm.objects(Picture.self).sorted(byKeyPath: "date", ascending: false)
like image 75
Grumme Avatar answered Mar 16 '23 10:03

Grumme