删除功能(提交editingStyle函数)会在按下滑动删除按钮后导致应用程序崩溃

时间:2016-11-09 05:37:16

标签: ios swift uitableview swift3

我正在研究swift 3.0中的一个项目,我正在将核心数据中的数据提取到两个tableViews上;' recurringIncomeTableView '和& #39;的 otherIncomeTableView &#39 ;.但是当提交editStyle'函数被激活(一旦我滑动行),我可以删除&rechuringIncomeTableView'中的特定行。但当我在“其他收入表”中滑动一行时并按下删除,在行' let task = stores [indexPath.row]'导致问题,应用程序崩溃。代码如下所示。

import UIKit
import CoreData

class MyIncomesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    @IBOutlet weak var recurringIncomeTableView: UITableView!
    @IBOutlet weak var otherIncomeTableView: UITableView!
    //var myIncomeType : String?

    var stores = [UserIncome] ()
    var other = [UserIncome] ()
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext



    override func viewDidLoad() {
        self.recurringIncomeTableView.reloadData()
        self.otherIncomeTableView.reloadData()
}

   override func viewDidAppear(_ animated: Bool) {

        stores.removeAll()
        other.removeAll()

        let request = NSFetchRequest <NSFetchRequestResult> (entityName: "UserIncome")
        request.returnsObjectsAsFaults = false



        do {

            let results = try context.fetch(request) as! [UserIncome]

            print("Results from the fetch request are : ", request)

            // check data existance
            if results.count>0 {
                print("results are :", results.count)

                for resultGot in results {

                    //lets check if the data is available and whether the loop is working by printing out the "name"
                    if let incName = resultGot.incomeName {
                        print("expence name is :", incName)

                        //set the value to the global variable as to filter the arrays 
                        let myIncomeType = resultGot.incomeType

                        if myIncomeType == "Recurring Income"{

                          stores += [resultGot]
                          print("my recurring income array is : \(stores)")
                        }else if myIncomeType == "Other Income"{

                          other += [resultGot]
                          print("my other income array is : \(other)")
                        }
                    }
                }
                self.recurringIncomeTableView.reloadData()
                self.otherIncomeTableView.reloadData()

            }

        }catch{


            print("No Data to load")
        }


    }
   @IBAction func addIncome(sender: UIButton) {
        print("Add Income Button Clicked")
        performSegue(withIdentifier: "ShowAddIncomeVC", sender: nil)
        // Do whatever you need when the button is pressed
    }


    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView == self.recurringIncomeTableView {
            print("recurringIncomeTableView count is ", stores.count)
         return stores.count
        }else {
            print("otherIncomeTableView count is ", other.count)
         return other.count
        }
    }

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

        if tableView == self.recurringIncomeTableView {
        let cell: RecuringIncomeTableViewCell = tableView.dequeueReusableCell(withIdentifier: "recurringIncomeCell") as! RecuringIncomeTableViewCell

        let store = stores [indexPath.row]

        cell.incomeNameLabel.text = store.incomeName
        cell.amountLabel.text = store.amount



        //cell.textLabel?.text = myExpensesArray[indexPath.row]
        return cell

        }else {
            let cell: OtherIncomeTableViewCell = tableView.dequeueReusableCell(withIdentifier: "otherIncomeCell") as! OtherIncomeTableViewCell

            let otherIncomes = other [indexPath.row]

            cell.incomeNameLabel.text = otherIncomes.incomeName
            cell.amountLabel.text = otherIncomes.amount


            //cell.textLabel?.text = myExpensesArray[indexPath.row]
            return cell

        }
    }




    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //performSegue(withIdentifier: "editStore", sender: nil)

    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "editRecurringIncome"{

            let v = segue.destination as! AddIncomeViewController
            let indexPath = self.recurringIncomeTableView.indexPathForSelectedRow
            let row = indexPath?.row
            v.store = stores[row!]

        }else if segue.identifier == "editOtherIncome" {
            let t = segue.destination as! AddIncomeViewController
            let indexPath = self.otherIncomeTableView.indexPathForSelectedRow
            let row = indexPath?.row
            t.store = other [row!]


        }
    }

//    

    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }

    //For remove row from tableview & object from array.
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

        if editingStyle == .delete {
            **let task = stores [indexPath.row]**
            context.delete(task)
            (UIApplication.shared.delegate as! AppDelegate).saveContext()

            do {
                stores = try context.fetch(UserIncome.fetchRequest())
            }catch{
                print("fail")
            }
        }
        tableView.reloadData()


    }

}

1 个答案:

答案 0 :(得分:-1)

根据您的Core data抓取请求代码。

您必须在商店阵列中存储core data个对象,而不是&amp;你可以直接从商店数组中删除那个对象。

你需要获取这样的对象:

// Initialize Fetch Request
let fetchRequest = NSFetchRequest()

// Create Entity Description
let entityDescription = NSEntityDescription.entityForName("UserIncome", inManagedObjectContext: self.managedObjectContext)

// Configure Fetch Request
fetchRequest.entity = entityDescription

store = try self.managedObjectContext.executeFetchRequest(fetchRequest)

获取所有数据后,您必须根据您的要求过滤数组并将其显示在tableview中我只是举例说明如何在tableview中显示该数据。

在单元格中显示您的数据:

var data: NSManagedObject = store[indexPath.row] as NSManagedObject
Cell.textLabel?.text = data.valueForKeyPath("Name") as? String 

根据您的代码删除您的数据:

let task = stores [indexPath.row]
context.delete(task)
(UIApplication.shared.delegate as! AppDelegate).saveContext()

它可以帮助您了解core datatableview的流量。