ios - 使用 CoreData 在 TableView 顶部插入新行

标签 ios swift uitableview core-data

我想使用 CoreData 制作一个应用程序。 我创建了 TableView 并添加了 View Controller 以将数据添加到核心数据中,并创建了 TableView 以检索数据并且一切正常。但是当我从添加 View Controller 向 TableView 插入新行时,它会转到 TableView 的底部。我想让它插入到表格 View 的顶部。我尝试了来自 Internet 的不同代码,但没有一个适用于我的代码。

这是 TableView Controller :

var List: [NSManagedObject] = []

override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .white
    // Configure Table View...
    tableView.separatorColor = .clear
}

override func viewDidAppear(_ animated: Bool) {
    let application: AppDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = application.persistentContainer.viewContext
    let get = NSFetchRequest<NSManagedObject>(entityName: "Entity")
    List = try! context.fetch(get)
    tableView.reloadData()
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return List.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MainCell", for: indexPath) as! MainTableViewCell
    let data: NSManagedObject = List[indexPath.row]
    cell.objectName.text = data.value(forKey: "objectName") as? String
    cell.objectPlace.text = data.value(forKey: "placeName") as? String
    return cell
}

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 180
}

最佳答案

默认情况下,核心数据对象按照插入的顺序获取。要首先显示最后添加的对象,只需反转获取的数组即可。

override func viewDidAppear(_ animated: Bool) {
  guard let application = UIApplication.shared.delegate as? AppDelegate else {
    return
  }
  let context = application.persistentContainer.viewContext
  let get = NSFetchRequest<NSManagedObject>(entityName: "Entity")
  do {
    List = try context.fetch(get).reversed()
    tableView.reloadData()
  } catch let error as NSError {
    print(error.userInfo)
  }
}

关于ios - 使用 CoreData 在 TableView 顶部插入新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57234400/

相关文章:

ios - json 解析时无法使用 Codable Concept swift 4 管理 nil

ios - 设置 SKShapeNode 一个角的半径

swift - Tableview 附件无法正确加载

ios - 如何在 UITableView 中设置 UILabel 的 Action

ios - 使用 STTwitterAPI 使用 twitter 登录一次

ios - UIColor colorWithString 给我一个错误 iOS

swift - AlamofireImage 缓存在我的应用程序中不起作用

ios - 如何设置一个 ViewController 上 UILabel 上的文本以从另一个 ViewController 中提取?

ios - Collection View 单元格之间的可用空间分布

iphone - 具有多列的 UITableView