swift - 如何使用 coredata 从上到下对 tableview 项目进行排序

标签 swift uitableview core-data swift3

我正在尝试在 tableView 中创建一个名称列表,并将其从上到下排序,我正在使用 coreData 保存所有信息,但是当我重新启动我的应用程序时,我的 tableView 是从下到上而不是从上到下排序的底部。

我尝试过许多其他方式,但对此感到很困惑。

我的核心数据实体“人”,里面有“名字”

import UIKit
import CoreData

var newList = [Person]()
var currentList = [Person]()
var myIndex = 0

class TableViewVC_SmartAccounting: UIViewController,UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UITextFieldDelegate {

@IBOutlet weak var txtField: UITextField!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var outAdd: UIButton!
@IBOutlet weak var searchBar: UISearchBar!

override func viewDidLoad() {
    super.viewDidLoad()
    fetchData()
    newList = currentList
    searchBar.backgroundImage = UIImage()
    txtField.returnKeyType = UIReturnKeyType.done
    txtField.delegate = self
}

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

}


func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    txtField.resignFirstResponder()
    print("RETURN")
    return true
}

func fetchData(){

    let fetchRequist: NSFetchRequest<Person> = Person.fetchRequest()
    do {
        let listFetched = try PersistenceService.context.fetch(fetchRequist)
        currentList = listFetched
        self.tableView.reloadData()
    } catch let err as NSError {
        print("Field to fetch an item", err)
    }
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return currentList.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCellVC_SmartAccounting
    cell.lblName.text = currentList[indexPath.row].name
    return cell
}

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {

    if editingStyle == .delete {

        let person = currentList.remove(at: indexPath.row)
        PersistenceService.context.delete(person)
        PersistenceService.saveContext()
        self.tableView.deleteRows(at: [indexPath], with: .fade)
    }
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    myIndex = indexPath.row
    performSegue(withIdentifier: "segue", sender: self)
    tableView.deselectRow(at: indexPath, animated: true)
}

func addPerson(){
    if txtField.text != ""{

        let person = Person(context: PersistenceService.context)
        person.name = txtField.text
        PersistenceService.saveContext()
       // currentList.append(person)
        currentList.insert(person, at: myIndex)
        view.endEditing(true)
        newList = currentList
        let indexPath = IndexPath(row: myIndex, section: 0)
        tableView.insertRows(at: [indexPath], with: .left)

       // tableView.insertRows(at: [IndexPath(row: list.count - 1, section: 0)], with: .automatic)
    }
    txtField.text = ""
    self.view.endEditing(true)


}

func setUpSearchBar() {
    searchBar.delegate = self
}

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    self.searchBar.endEditing(true)
}

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    guard !searchText.isEmpty else {currentList = newList
        tableView.reloadData()
        return }
    currentList = newList.filter ({ (Person) -> Bool in
        (Person.name?.lowercased().contains(searchText.lowercased()))!
    })
    tableView.reloadData()
}

func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
}

@IBAction func btnAdd(_ sender: Any) {
    addPerson()
}

最佳答案

  • Person 实体中添加 Int32 类型的属性 index
  • 在 Controller 中添加一个方法来重新索引currentList并保存上下文

    func reindex()
    {
        for (index, person) in currentList.enumerated() {
            person.index = Int32(index)
        }
        PersistenceService.saveContext()
     }
    
  • fetchData中添加一个排序描述符

    fetchRequist.sortDescriptors = [NSSortDescriptor(key: "index", ascending: true)] 
    
  • 插入对象后重新索引数组

    let person = Person(context: PersistenceService.context)
    person.name = txtField.text
    person.index = Int32(myIndex)
    currentList.insert(person, at: myIndex)
    let indexPath = IndexPath(row: myIndex, section: 0)
    tableView.insertRows(at: [indexPath], with: .left)
    reindex()
    view.endEditing(true)
    newList = currentList
    
  • 并且在删除一个对象后也重新索引数组

    if editingStyle == .delete {
        let person = currentList.remove(at: indexPath.row)
        PersistenceService.context.delete(person)
        self.tableView.deleteRows(at: [indexPath], with: .fade)
        reindex()
    }
    

关于swift - 如何使用 coredata 从上到下对 tableview 项目进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54060762/

相关文章:

ios - 使用 iOS 的 Firebase Google Auth

ios - 如何删除 UITableViewCell 第一行的垂直间距

ios - 如何更改 UITableViewCell 中的元素标题?

ios - UITableViewCell 框架高度与 tableView 不匹配 :heightForRowAtIndexPath:

ios - 访问 UILocalNotification 用户信息时出现 Swift 错误

ios - 从 firebase 实时数据库中检索当前用户 (Swift 4/5)

Swift Core Data 获取数据 1 列

objective-c - 核心数据合并两个托管对象上下文

ios - 魔法记录导入(下一步)

ios - Swift NSNotificationCenter 在其他类中添加观察者功能