Search code examples
iosswiftuitableviewcore-data

Insert new row on top of table view with CoreData


I want to make an app using CoreData. I made the table view and add view controller to add data into Core Data and the table view to retrieve data and everything worked normal. But when I insert a new row from add view controller to the table view, it is going to the bottom of table view. I want to make it insert on top of the table view. I tried different code from the Internet but none worked with my code.

This is Table View 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
}

Solution

  • By default core data objects are fetched in the order they are inserted. To show the last added objects at first just reverse the fetched array.

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