2016-11-09 10 views
-3

コアデータからのデータをSwift 3.0およびImでプロジェクトに取り込んでいます。 recurringIncomeTableView '、および' otherIncomeTableView 'となります。しかし、 'commit editingStyle'関数がアクティブになると(行をスライドさせると)、 'recurringIncomeTableView'の特定の行を削除できます。しかし、 'otherIncomeTableView'の行をスライドさせてを削除すると、 '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() 


    } 

} 
+2

質問に完全なエラーメッセージを含める必要があります。 – rmaddy

+0

他のテーブルから削除するときに 'stores'配列ではなく、' other'配列にアクセスしてはいけませんか? – 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

はこのように、セルにデータを表示:

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

それはtableviewcore dataの流れを理解するのに役立ちます。

+0

これには欠落している部分があります。 'viewController'が読み込まれたときだけデータを取得する場合は、コンテキストから削除して配列から削除する必要があります。 (あなたは配列からそれを削除していません) – ELKA

+0

私はちょうど彼が間違いをしている場所を言及しているので、彼はクラッシュから出てくることができるので、部分ユーザーは実装する必要があります。これ以上の詳細は必要ありません@ELKA – CodeChanger

+0

あなたは完全なコードを入れられますか?上記のコードには、uが示すように部品が欠落しています。 – danutha

関連する問題