2016-11-09 25 views
-3

我在swift 3.0中的項目中工作,Im從中獲取數據到兩個tableViews上;'' recurringIncomeTableView','otherIncomeTableView'。但是,當'commit editingStyle'函數被激活(一旦我滑動該行),我可以刪除'recurringIncomeTableView'中的特定行。但是,當我在'otherIncomeTableView'中滑動一行並按下刪除時,在'let task = stores [indexPath.row]'行中導致問題,應用程序崩潰。代碼如下。刪除功能(commit editingStyle功能)一旦按下滑動刪除按鈕導致應用程序崩潰

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


    } 

} 
+2

你需要在你的問題中包含完整的錯誤信息。 – rmaddy

+0

從另一個表中刪除時不應該訪問'other'數組,而不是'stores'數組? – Paulw11

+0

從哪個表中刪除您的行? 'self.recurringIncomeTableView'或'self.otherIncomeTableView'?也請在你的問題中提及你的崩潰。 – CodeChanger

回答

-1

根據您的Core data獲取請求代碼。

您必須存儲core data對象的存儲陣列比&比你可以直接刪除對象構成存儲陣列。

都需要這樣的獲取對象:

// 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 data流與tableview

+0

這是有一些缺少的部分。如果你只在'viewController'加載的時候獲取數據,你應該從上下文中刪除它並從數組中刪除它。 (你沒有將它從數組中移除) – ELKA

+0

該部分用戶需要實現,因爲我剛纔提到他在做錯誤,他可以從崩潰中出來。所以不需要額外的細節@ELKA – CodeChanger

+0

先生你可以把完整的代碼。上面的代碼有缺失的部分,就像你說的那樣。 – danutha