在Swift 3中按字母顺序排序Realm对象

4

我有一个通讯录,想要将 Realm 对象(联系人)按字母顺序排序,我跟随了一些教程,但是出现了一些问题,如图片所示:

enter image description here

这是我的代码:

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)
    }
}

联系人.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 = ""

}

我应该如何按最后联系人添加时间排序呢?就像iPhone上电话应用程序中的联系人选项卡一样...

祝好 <3


1
请参考有关排序的文档 https://realm.io/docs/swift/latest/#sorting - EpicPandaForce
@EpicPandaForce 我看了那个,但是不知道如何在我的项目中实现。 - AmirMohammad Gholami
1
不要试图应用排序规则,而是获取一个已排序的数据集,而不仅仅是 return realm.objects(ContactItem.self) - EpicPandaForce
1个回答

19

你需要按升序排序你领域的查询结果。例如,尝试这个:

var ContactList: Results<ContactItem> {
    get {
        return realm.objects(ContactItem.self).sorted(byKeyPath: "your property", ascending: true)
    }
}

1
例如,如果您想按名称字母顺序排序,则需要输入.sorted(byKeyPath: "name", ascending: true) - Alfredo Luco G
现在我该如何按部分字母顺序对tableView中的数据进行排序?就像iPhone的电话应用程序中的联系人一样...这对我来说很必要... - AmirMohammad Gholami
1
你可以使用 Realm 的过滤器。例如,如果要筛选以字母 a 开头的部分,你需要输入 filter("name BEGINSWITH 'a' ") - Alfredo Luco G
2
`func sectionNames(alphabet: String)->Results<ContactItem>{ return realm.objects(ContactItem.self).filter("name BEGINSWITH[cd] (alphabet)").sorted(byKeyPath: "name", ascending: true)}` - Alfredo Luco G
我应该在哪里使用这个?请编辑我的代码并给我,我很困惑... :( - AmirMohammad Gholami
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接