如何删除表视图核心数据中的行。斯威夫特3

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何删除表视图核心数据中的行。斯威夫特3相关的知识,希望对你有一定的参考价值。

我一直在研究如何从表视图中删除数据在Core Data中的行。我找不到任何可以帮助我处理代码的在线内容。我是Core Data的新手,所以我对它并不是很了解。

提前致谢

这是我的代码

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

    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return}

    let managedContext = appDelegate.persistentContainer.viewContext

    let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "OfficialPT")
    fetchRequest.sortDescriptors = [NSSortDescriptor(key:"createdAt",ascending:false)]


    do {
        AirForceDatabase = try managedContext.fetch(fetchRequest)
    } catch let error as NSError {
        print("Could not fetch. (error), (error.userInfo)")
    }
}

func SideMenus ()
{
    if revealViewController() != nil {
        MenuButton.target = revealViewController()
        MenuButton.action = #selector(SWRevealViewController.revealToggle(_:))
        revealViewController().rearViewRevealWidth = 275
        revealViewController().rightViewRevealWidth = 160

        // profileButton.target = revealViewController()
        // profileButton.action = #selector(SWRevealViewController.rightRevealToggle(_:))

        view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())


    }
}

}

扩展HistoryPTViewController:UITableViewDataSource {

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


func tableView(_ tableView: UITableView,
               cellForRowAt indexPath: IndexPath) -> UITableViewCell {




    if let cell = tableView.dequeueReusableCell(withIdentifier: "Cell",for: indexPath) as? HistoryPTTableViewCell {


    let person = AirForceDatabase[indexPath.row]

       cell.OfficialAbsLbl!.text = person.value(forKeyPath: "officialAbs")! as? String
        cell.OfficialPushLbl!.text = person.value(forKeyPath: "officialPush")! as? String
        cell.OfficialSitLbl!.text = person.value(forKeyPath: "officialSit")! as? String
        cell.OfficialRunLbl!.text = person.value(forKeyPath: "officialRun")! as? String
        cell.officialTotal!.text = person.value(forKeyPath: "totalScore")! as? String
        cell.officialdateCreated.text = person.value(forKeyPath: "createdAt")! as? String







    return cell
}
return UITableViewCell()

}

扩展HistoryPTViewController:UITableViewDelegate {

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)

     let person = AirForceDatabase[indexPath.row]
    //Convert String to Double
    if let score = person.value(forKeyPath: "totalScore")! as? String, let doubleScore = Double(score) {

        officialTotalScore = doubleScore
        //officialTotalScore = Double(score)

        print("Score (officialTotalScore)")

    }
    var createdat :String!

    CompostiveLbl.text = "Composite Score:
(officialTotalScore)%"
    createdat = person.value(forKeyPath: "createdAt")! as? String
    print(createdat + "CREATED")
    if officialTotalScore >= 90 {
        print("Excellent")

        officialFinalScoreLbl.text = "Fitness Level:
 Excellent"
    }else if officialTotalScore >= 75 && officialTotalScore <= 89.9 {


        print("Composite Score: Satisfactory")
        officialFinalScoreLbl.text = "Fitness Level:
 Satisfactory"

    }else if  officialTotalScore <= 75 {

        print("Composite Score: Unsatisfactory")
        officialFinalScoreLbl.text = "Fitness Level:
  Unsatisfactory"
    }





    let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = DateFormatter.Style.long
    dateFormatter.dateFormat = "yyyy-MM-dd"
    let convertedDate = dateFormatter.date(from: createdat)
    dateFormatter.dateFormat = "MMM dd yyyy"
    let date = dateFormatter.string(from: convertedDate!)

    NextPTLbl.text = "Test Date:
" + date
}


func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

       let person = AirForceDatabase[indexPath.row]
    if editingStyle == .delete {






   }


}
答案

每当tableview处理Core Data时,你应该总是使用“NSFetchedResultsController”,因为构建了“NSFetchedResultsController”,记住了tableView。

它提供了有助于处理tableView的功能

  1. 与UITableViewDelegate和UITableviewdatasource协议一起,采用/符合“NSFetchedResultsControllerDelegate”协议。
  2. 然后实现其3种方法从核心数据中删除记录。并且不要重新查看tableview。 NSFetchedResultsController会处理它。

例如。让我们从核心数据加载数据(实体名称=电影)

var fetchedResultsController: NSFetchedResultsController<Movie>

override func viewDidLoad()
{
    super.viewDidLoad()
    loadData()
}

func loadData() 
{
        fetchedResultController = getMovies(managedObjectContext: self.coreData.persistentContainer.viewContext)
        fetchedResultController.delegate = self
}


func getMovies(managedObjectContext: NSManagedObjectContext) -> NSFetchedResultsController<Movie> 
{
        let fetchedResultController: NSFetchedResultsController<Movie>

        let request: NSFetchRequest<Movie> = Movie.fetchRequest()
        let formatSort = NSSortDescriptor(key: "format", ascending: false)
        let nameSort = NSSortDescriptor(key: "title", ascending: true)
        request.sortDescriptors = [formatSort, nameSort]

        fetchedResultController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: managedObjectContext, sectionNameKeyPath: "format", cacheName: "MyMovieLibrary")

        do
        {
            try fetchedResultController.performFetch()
        }
        catch
        {
            fatalError("Error in fetching records")
        }

        return fetchedResultController
}

// MARK: - 表视图数据源

override func numberOfSections(in tableView: UITableView) -> Int
{
    if let sections = fetchedResultController.sections
    {
        return sections.count
    }
    return 0
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    if let sections = fetchedResultController.sections
    {
        let currentSection = sections[section]
        return currentSection.numberOfObjects
    }
    return 0
}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    let cell = tableView.dequeueReusableCell(withIdentifier: "movieCell", for: indexPath) as! MovieTableViewCell

    let movie = fetchedResultController.object(at: indexPath)
    cell.configureCell(movie: movie)

    return cell
}

从核心数据中删除记录

// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath)
{
    let managedObjectContext = coreData.persistentContainer.viewContext

    if editingStyle == .delete
    {
        movieToDelete = fetchedResultController.object(at: indexPath)

        let confirmDeleteAlertController = UIAlertController(title: "Remove Movie", message: "Are you sure you would like to delete "(movieToDelete!.title!)" from your movie library?", preferredStyle: UIAlertControllerStyle.actionSheet)

        let deleteAction = UIAlertAction(title: "Delete", style: UIAlertActionStyle.default, handler: { [weak self] (action: UIAlertAction) -> Void in
            managedObjectContext.delete((self?.movieToDelete!)!)
            self?.coreData.saveContext()
            self?.movieToDelete = nil
        })

        let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: { [weak self] (action: UIAlertAction) -> Void in
            self?.movieToDelete = nil
        })

        confirmDeleteAlertController.addAction(deleteAction)
        confirmDeleteAlertController.addAction(cancelAction)

        present(confirmDeleteAlertController, animated: true, completion: nil)

    }
}

func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>)
    {
        tableView.beginUpdates()
    }

func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?)
{
    switch type
    {
    case NSFetchedResultsChangeType.delete:
        print("NSFetchedResultsChangeType.Delete detected")
        if let deleteIndexPath = indexPath
        {
            tableView.deleteRows(at: [deleteIndexPath], with: UITableViewRowAnimation.fade)
        }
    case NSFetchedResultsChangeType.insert:
        print("NSFetchedResultsChangeType.Insert detected")
    case NSFetchedResultsChangeType.move:
        print("NSFetchedResultsChangeType.Move detected")
    case NSFetchedResultsChangeType.update:
        print("NSFetchedResultsChangeType.Update detected")
        tableView.reloadRows(at: [indexPath!], with: UITableViewRowAnimation.fade)
    }
}

func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>)
{
    tableView.endUpdates()
}

以上是关于如何删除表视图核心数据中的行。斯威夫特3的主要内容,如果未能解决你的问题,请参考以下文章

在 iOS7 中使用核心数据删除表格视图中的行的奇怪行为

从表视图中删除行

使用Swift 3和CoreData删除表视图行

删除子视图中的核心数据后更新表视图

如何使用tableview删除核心数据中的数据

删除带有节标题的表视图中的行