0

我在一個視圖控制器中擁有兩個表視圖,這兩個視圖控制器都擁有彼此不相關的不同類型的數據。出於某種原因,無論何時向任何項目添加新數據,應用程序崩潰都會將新數據添加到兩個表視圖中,而不是僅添加一個。我試圖將數據添加到正確的表格視圖。這是我的代碼。當我將核心數據添加到表視圖時,我的應用崩潰

var tasks: Todo! 
var progress: [Millestone] = [] 
var milestone: Millestone! 
var list: [Todo] = [] 

var taskfetch: NSFetchedResultsController<Todo>! 
var progressfetch : NSFetchedResultsController<Millestone>! 


    let fetching: NSFetchRequest<Todo> = Todo.fetchRequest() 
    let sorting = NSSortDescriptor(key: "dateadded", ascending: true) 
    fetching.predicate = NSPredicate(format: "projectname = %@", "\(title! as String)") 
    fetching.sortDescriptors = [sorting] 
    if let appDelegate = (UIApplication.shared.delegate as? AppDelegate) { 
     let context = appDelegate.persistentContainer.viewContext 
     taskfetch = NSFetchedResultsController(fetchRequest: fetching, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil) 
     taskfetch.delegate = self 

     do { 
      try taskfetch.performFetch() 
      if let fetchedObjects = taskfetch.fetchedObjects { 
       list = fetchedObjects 
      } 
     } catch { 
      print(error) 
     } 
    } 

    let lining: NSFetchRequest<Millestone> = Millestone.fetchRequest() 
    let sorting2 = NSSortDescriptor(key: "dateadded", ascending: true) 
    lining.predicate = NSPredicate(format: "projectname = %@", "\(title! as String)") 
    lining.sortDescriptors = [sorting2] 
    if let appDelegate = (UIApplication.shared.delegate as? AppDelegate) { 
     let context = appDelegate.persistentContainer.viewContext 
     progressfetch = NSFetchedResultsController(fetchRequest: lining, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil) 
     progressfetch.delegate = self 

     do { 
      try progressfetch.performFetch() 
      if let fetchedObjects = progressfetch.fetchedObjects { 
       progress = fetchedObjects 
      } 
     } catch { 
      print(error) 
     } 
    } 
func getdata() { 
    let context = (UIApplication.shared.delegate as! AppDelegate!).persistentContainer.viewContext 

    do { 
     print("getting") 


     let tasking = try context.fetch(Todo.fetchRequest()) 


     let progressname = try context.fetch(Millestone.fetchRequest()) 
    } catch{ 
     print("whoopsie") 
    } 
} 
let oktaskaction = UIAlertAction(title: "Add", style: .default, handler: {(action:UIAlertAction!) -> Void in 

     if text.textFields?[0].text != nil, text.textFields?[0].text != "" { 
      // self.taskTable.beginUpdates() 
      // let song = self.songs[indexPath.row] 
      //(UIApplication.shared.delegate as! AppDelegate).saveContext() 
      if let appDelegate = (UIApplication.shared.delegate as? AppDelegate){ 
       self.tasks = Todo(context: appDelegate.persistentContainer.viewContext) 
       self.tasks.taskname = text.textFields?[0].text 
       self.tasks.projectname = self.title 
       self.tasks.completed = false 
       let formatter = DateFormatter() 
       formatter.dateStyle = DateFormatter.Style.medium 
       formatter.timeStyle = DateFormatter.Style.none 
       self.tasks.dateadded = self.date 
       appDelegate.saveContext() 
      }else { 
       print("nothing there") 
       text.textFields?[0].placeholder = "did not enter text" 
      } 
      self.taskTable.refreshControl?.beginRefreshing() 
      self.getdata() 
      self.taskTable.reloadData() 

     } 

    }) 


    let okAction = UIAlertAction(title: "Add Milestone", style: .default, handler: {(action:UIAlertAction!) -> Void in 
     if text2.textFields?[0].text != nil, text2.textFields?[0].text != "", text2.textFields?[1].text != nil { 
      print("i'm working on adding the milestone") 
      if let appDelegate = (UIApplication.shared.delegate as? AppDelegate){ 
       self.milestone = Millestone(context: appDelegate.persistentContainer.viewContext) 
       self.milestone.progressname = text2.textFields?[0].text 
       self.milestone.date = text2.textFields?[1].text 
       self.milestone.projectname = self.title 
       appDelegate.saveContext() 
        print("adding to graph") 
        self.chartLegend.append(self.milestone.progressname!) 
        self.chartData.append(self.chartData.count + 1) 


       print("saved the new milestone") 
      }else { 
       print("nothing there") 
       text.textFields?[0].placeholder = "did not enter text" 
      } 
      self.milestoneTableView.reloadData() 
      self.projectlinechart.reloadData() 

     } 

    }) 
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { 
    print("Begining") 
    print("\(list.count)") 
    print("\(progress.count)") 
    taskTable.beginUpdates() 
    milestoneTableView.beginUpdates() 

} 
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { 
    switch type { 
    case .insert: 

     if let newIndexPath = newIndexPath { 
       print("adding") 

      taskTable.insertRows(at: [newIndexPath], with: .fade) 
      milestoneTableView.insertRows(at: [newIndexPath], with: .fade) 

     } 
    case .delete: 
     if let indexPath = indexPath { 
      print("delete") 
      taskTable.deleteRows(at: [indexPath], with: .fade) 
      milestoneTableView.deleteRows(at: [indexPath], with: .fade) 

     } 
    case .update: 
     if let indexPath = indexPath { 
      print("updating") 
      taskTable.reloadRows(at: [indexPath], with: .fade) 
      milestoneTableView.reloadRows(at: [indexPath], with: .fade) 

     } 
    default: 
     print("doing something else") 
     taskTable.reloadData() 
     milestoneTableView.reloadData() 

    } 

    if let fetchedObjects = controller.fetchedObjects { 
     projects = fetchedObjects as! [Project] 
     list = fetchedObjects as! [Todo] 
     progress = fetchedObjects as! [Millestone] 
    } 
} 
    func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { 
     print("ending") 
     print("\(list.count)") 
     print("\(progress.count)") 
     taskTable.endUpdates() 
     milestoneTableView.endUpdates() 



    } 
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    if tableView.tag == 1 { 
     return list.count 
    } else if tableView.tag == 2 { 
     return progress.count 
    } else { 
     return 0 
    } 
     } 


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cellidentifier = "taskcell" 

    let cell = tableView.dequeueReusableCell(withIdentifier: cellidentifier, for: indexPath) as! TaskTableViewCell 
    if tableView.tag == 1 { 
     let tasks = list[indexPath.row]//this is where the crash occurs 
     cell.taskname.text = tasks.taskname 
     cell.taskname.adjustsFontSizeToFitWidth = true 
     if tasks.completed == true { 
      cell.accessoryType = .checkmark 
     } 



    } 
    } else if tableView.tag == 2 { 
     if let appDelegate = (UIApplication.shared.delegate as? AppDelegate){ 
      let progress2 = progress[indexPath.row] 
      if (progress2.progressname != nil), progress2.date != nil{ 
      cell.progressname.text = "\(progress2.progressname!) on \(progress2.date!)" 
      cell.progressname.adjustsFontSizeToFitWidth = true 
      self.chartData.append(self.chartData.count + 1) 
      chartLegend.insert(cell.progressname.text!, at: indexPath.row) 
      } else { 
       cell.progressname.text = "No Milestones" 
      } 

     } 

    } 


    return cell 
} 
+0

您可以分享應用程序崩潰的位置以及您收到的錯誤消息嗎?這段代碼 –

+0

確保應用程序崩潰讓任務列表= [indexPath.row] 我得到的錯誤是致命的錯誤:NSArray的元素眼福雨燕陣列 –

+0

添加異常斷點,然後再次運行。一般來說,如果這是一個核心數據問題,它會清楚地報告發生了什麼並停止在線。同時共享控制檯輸出將非常有幫助。 –

回答

0

擺脫以下變量progresslist的。 fetchedResultsController正在跟蹤對象的變化,所以當一個對象被刪除,插入或移動時它會爲你更新。通過將獲取的結果複製到數組中,您可以在發生更改後查看過時的信息。相反,看看直接在fetchedResultsController的值(即接入self.taskfetch.fetchedObjects或使用self.taskfetch.object(at:indexPath)

這導致崩潰的原因是因爲你的基礎上修改的fetchedResultsController(一個或多個)的通知您,而不是更新的tableview更新表格中的行數,因爲您查看的是陳舊的數據

另一個問題是,當兩組數據中的任何一組數據發生更改時,您正在更新BOTH表。在所有的控制器方法中,首先檢查它是哪個控制器,類似於if controller == taskfetch {

+0

是否有可能我需要使兩種不同的方式改變每組數據的funcs? –

+0

我已經更新了我的回答,地址是 –

+0

謝謝,這是它 –

相關問題