OGeek|极客世界-中国程序员成长平台

标题: ios - 如何使用 Core Data 按部分按字母顺序对 tableView 中的数据进行排序? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 20:00
标题: ios - 如何使用 Core Data 按部分按字母顺序对 tableView 中的数据进行排序?

我是 Swift 3 编码的新手。 我正在尝试从 iPhone “复制”电话应用程序,但是在单元格中显示数据时遇到了一些问题,它们没有出现(当那里显然有一些数据时,从 Core Data 类中恢复)。 Core Data 类由一个带有一些属性的联系人组成,如“firstName”、“lastName”、“phoneNumber”等。我在 X.xcdatamodeld 中创建了它。那些属性 设置在另一个 VC 中并保存在那里。 我想在单元格中显示的是按字母顺序按部分排序的每个联系人的名字,例如电话应用程序。 这是我目前所拥有的。

extension Contact {
var titleFirstLetter: String {
    return String(firstName![firstName!.startIndex]).uppercased()
 }
}

class MainTableViewController: UITableViewController {
var listOfContacts = [Contact]() 
var sortedFirstLetters: [String] = []
var sections: [[Contact]] = [[]]

struct Storyboard {
    static let cellIdentifier = "Cell"
    static let showDetailIdentifier = "showDetail"
    static let showInformationIdentifier = "showInformationVC"
}

 override func viewDidLoad() {
    super.viewDidLoad()

    tableView.delegate = self
    tableView.dataSource = self

    let firstLetters = listOfContacts.map { $0.titleFirstLetter }

    let uniqueFirstLetters = Array(Set(firstLetters))

    sortedFirstLetters = uniqueFirstLetters.sorted()
    sections = sortedFirstLetters.map { firstLetter in
        return listOfContacts.filter { $0.titleFirstLetter == firstLetter }.sorted { $0.firstName! < $1.firstName! }
    }
 }

 override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    getData()
    tableView.reloadData()
 }

 func getData() {
    // 1. Create context
    let context = CoreDataController.persistentContainer.viewContext

    // 2. RecoverData from Database with fetchRequest
    do {
        try listOfContacts = context.fetch(Contact.fetchRequest())
    } catch {
        print("Error \(error.localizedDescription)")
    }
}

// MARK: - Tableview data source

override func numberOfSections(in tableView: UITableView) -> Int {
     return sections.count
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return sections[section].count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let contact = sections[indexPath.section][indexPath.row]

    let cell = tableView.dequeueReusableCell(withIdentifier: Storyboard.cellIdentifier, for: indexPath)
    cell.textLabel?.text = contact.firstName

    return cell
}

 override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
    return sortedFirstLetters
}


override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
   return sortedFirstLetters[section]
}

注意:CoreDataController 是我在管理检索和保存到 CoreData 时使用的一个类(我所做的是从 AppDelegate.swift 复制生成的 CoreData 代码) 希望您能帮助我弄清楚为什么它不起作用。提前致谢!



Best Answer-推荐答案


Should use NSSortDescriptor with your fetched query like:

  let sectionSortDescriptor = NSSortDescriptor(key: "first_name", ascending: true)
  let sortDescriptors = [sectionSortDescriptor]
 fetchRequest.sortDescriptors = sortDescriptors
 let fetchedPerson = try context.fetch(fetchRequest) as! [Contact]

它可能会解决您的问题。如果您在此之后遇到问题,请告诉我。

关于ios - 如何使用 Core Data 按部分按字母顺序对 tableView 中的数据进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44860316/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4