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

时间:2017-12-27 10:23:05

标签: xcode uitableview core-data swift3 iphonecoredatarecipes

我一直在研究如何从数据在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:\n\(officialTotalScore)%"
    createdat = person.value(forKeyPath: "createdAt")! as? String
    print(createdat + "CREATED")
    if officialTotalScore >= 90 {
        print("Excellent")

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


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

    }else if  officialTotalScore <= 75 {

        print("Composite Score: Unsatisfactory")
        officialFinalScoreLbl.text = "Fitness Level:\n  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:\n" + date
}


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

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






   }


}

1 个答案:

答案 0 :(得分:7)

每当tableview处理核心数据时,你应该总是使用“NSFetchedResultsController”,因为“NSFetchedResultsController”是建立在保持tableView的基础上的。

它提供了对处理tableView

有用的功能
  1. 与UITableViewDelegate&amp; UITableviewdatasource协议,采用/符合“NSFetchedResultsControllerDelegate”协议
  2. 然后实现其3种方法从核心数据中删除记录。并且不要重新加载tableview 。 NSFetchedResultsController会处理它。
  3. 例如。让我们从核心数据(实体名称=电影)

    加载数据
    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()
    }