首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用coredata从上到下对表视图项进行排序

如何使用coredata从上到下对表视图项进行排序
EN

Stack Overflow用户
提问于 2019-01-06 18:49:11
回答 1查看 87关注 0票数 0

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

我试着使用许多其他的方法,但我对此感到很困惑。

我的coreData实体"Person“,里面有"name”

代码语言:javascript
复制
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()
}

}

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-01-06 20:40:05

控制器在Int32

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

func reindex() { for (索引,人员) in currentList.enumerated() { person.index =Int32(索引)} PersistenceService.saveContext() }

  • In fetchData添加排序描述符

fetchRequist.sortDescriptors = NSSortDescriptor(key:"index",升序: true)插入对象后对数组重新编制索引的

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

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54060762

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档