Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Realm Objects Alphabetically in Swift 3

i have a PhoneBook that want to Sort Realm Objects ( Contacts ) Alphabetically , i followed some Tutorials , but i have Some Problems that Showed in Picture :

enter image description here

and my Codes are :

MainVC.swift :

import UIKit
import RealmSwift

class MainVC: UIViewController,UITableViewDelegate,UITableViewDataSource {

@IBOutlet weak var contact_tableview: UITableView!

var contactsWithSections = [[ContactItem]]()

var sectionTitles = [String]()

let realm = try! Realm()

var ContactList: Results<ContactItem> {
    get {
        return realm.objects(ContactItem.self)
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationController?.navigationBar.titleTextAttributes =
        [NSFontAttributeName: UIFont(name: "IRANSansWeb-Medium", size: 17)!]
    contact_tableview.delegate = self
    contact_tableview.dataSource = self

    let (arrayContacts, arrayTitles) = collation.partitionObjects(array: ContactList, collationStringSelector: #selector(getter: ContactItem.first_name))

}





func numberOfSections(in tableView: UITableView) -> Int {

    return 1

}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {



    return ContactList.count

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


    let cell = tableView.dequeueReusableCell(withIdentifier: "ContactCell") as! ContactCell

    let item = ContactList[indexPath.row]

    cell.lblName!.text = item.first_name

    return cell

}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let ContactV = storyboard?.instantiateViewController(withIdentifier: "ViewContact") as! ContactInfoVC
    navigationController?.pushViewController(ContactV, animated: true)
    ContactV.ContactID = ContactList[indexPath.row]
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    contact_tableview.reloadData()
    // to reload selected cell
}





}



let collation = UILocalizedIndexedCollation.current()

extension UILocalizedIndexedCollation {
    //func for partition array in sections
    func partitionObjects(array:[AnyObject], collationStringSelector:Selector) -> ([AnyObject], [String]) {
        var unsortedSections = [[AnyObject]]()
        //1. Create a array to hold the data for each section
        for _ in self.sectionTitles {
            unsortedSections.append([]) //appending an empty array
        }
        //2. Put each objects into a section
        for item in array {
            let index:Int = self.section(for: item, collationStringSelector:collationStringSelector)
            unsortedSections[index].append(item)
        }
        //3. sorting the array of each sections
        var sectionTitles = [String]()
        var sections = [AnyObject]()
        for index in 0 ..< unsortedSections.count { if unsortedSections[index].count > 0 {
            sectionTitles.append(self.sectionTitles[index])
            sections.append(self.sortedArray(from: unsortedSections[index], collationStringSelector: collationStringSelector) as AnyObject)
            }
        }
        return (sections, sectionTitles)
    }
}

Contact.swift :

    import UIKit
import RealmSwift



class ContactItem : Object {

    dynamic var id:Int = 0
    dynamic var first_name = ""
    dynamic var last_name = ""
    dynamic var work_email = ""
    dynamic var personal_email = ""
    dynamic var contact_picture = ""
    dynamic var mobile_number = ""
    dynamic var home_number = ""
    dynamic var isFavorite = false
    dynamic var Notes = ""

}

and how i sort them of Last Contact Added to First ? Like Contact Tab in Phone Application in iPhone ...

Regards <3

like image 466
AmirMohammad Gholami Avatar asked Nov 30 '22 15:11

AmirMohammad Gholami


1 Answers

You need to sort you realm's query result with asc. For example try this:

var ContactList: Results<ContactItem> {
    get {
        return realm.objects(ContactItem.self).sorted(byKeyPath: "your property", ascending: true)
    }
}
like image 132
Alfredo Luco G Avatar answered Dec 05 '22 14:12

Alfredo Luco G