FRC内容更改时的UITableView异常

时间:2018-06-09 01:04:51

标签: ios swift uitableview nsfetchedresultscontroller

我有一个显示UITableView数据的NSFetchedResultsController。 FRC中显示的数据量不等,从一次提取的约20条记录到最大的一条记录的约14k条记录。我遇到的问题是,如果我在tableView滚动大型提取时执行提取,我会得到一个异常。到cellForRowAtIndexPath被调用时,FRC已经更新,那里没有数据,导致异常。

我找到this post,听起来就像我遇到过的那样,虽然我无法通过这种方法解决它。

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseID, for: indexPath) as! CustomTableViewCell
    // Exception occurs here
    let myObject = fetchedResultsController.object(at: indexPath)
    cell.myObject = myObject

    return cell
  }

这是堆栈跟踪:

0   CoreFoundation                      0x0000000110b241e6 __exceptionPreprocess + 294
1   libobjc.A.dylib                     0x000000010b820031 objc_exception_throw + 48
2   CoreData                            0x000000010c2458fd -[NSFetchedResultsController objectAtIndexPath:] + 685
3   MyApp                         0x000000010aaf36c5 _T011MyApp0B14ViewControllerC05tableC0So07UITableC4CellCSo0fC0C_10Foundation9IndexPathV12cellForRowAttF + 437
4   MyApp                         0x000000010aaf39ec _T011MyApp0B14ViewControllerC05tableC0So07UITableC4CellCSo0fC0C_10Foundation9IndexPathV12cellForRowAttFTo + 92
5   UIKit                               0x000000010cf45567 -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 783
6   UIKit                               0x000000010cf45ae4 -[UITableView _createPreparedCellForGlobalRow:willDisplay:] + 74
7   UIKit                               0x000000010cf0ceaa -[UITableView _updateVisibleCellsNow:isRecursive:] + 3168
8   UIKit                               0x000000010cf2d7e0 -[UITableView layoutSubviews] + 176
9   UIKit                               0x000000010ceb77a8 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1515
10  QuartzCore                          0x000000010cc21456 -[CALayer layoutSublayers] + 177
11  QuartzCore                          0x000000010cc25667 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 395
12  QuartzCore                          0x000000010cbac0fb _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 343
13  QuartzCore                          0x000000010cbd979c _ZN2CA11Transaction6commitEv + 568
14  UIKit                               0x000000010cde22ef _UIApplicationFlushRunLoopCATransactionIfTooLate + 167
15  UIKit                               0x000000010d747662 __handleEventQueueInternal + 6875
16  CoreFoundation                      0x0000000110ac6bb1 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
17  CoreFoundation                      0x0000000110aab4af __CFRunLoopDoSources0 + 271
18  CoreFoundation                      0x0000000110aaaa6f __CFRunLoopRun + 1263
19  CoreFoundation                      0x0000000110aaa30b CFRunLoopRunSpecific + 635
20  GraphicsServices                    0x0000000115c2fa73 GSEventRunModal + 62
21  UIKit                               0x000000010cde8057 UIApplicationMain + 159
22  MyApp                         0x000000010aacd427 main + 55
23  libdyld.dylib                       0x0000000111c5b955 start + 1

我欢迎解决此问题的建议。在tableview减速完成之前,我想避免像禁用新的提取这样的事情。谢谢你的阅读。

更新

在回复评论时,这是UIFetchedResultsControllerDelegate的实施。这是Apple在documentation中的代码:

extension ViewController: NSFetchedResultsControllerDelegate {
  func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    tableView.beginUpdates()
  }

  func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>,
                  didChange sectionInfo: NSFetchedResultsSectionInfo,
                  atSectionIndex sectionIndex: Int,
                  for type: NSFetchedResultsChangeType) {
    switch type {
    case .insert:
      tableView.insertSections(IndexSet(integer: sectionIndex), with: .fade)
    case .delete:
      tableView.deleteSections(IndexSet(integer: sectionIndex), with: .fade)
    case .move:
      break
    case .update:
      break
    }
  }

  func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>,
                  didChange anObject: Any,
                  at indexPath: IndexPath?,
                  for type: NSFetchedResultsChangeType,
                  newIndexPath: IndexPath?) {
    switch type {
    case .insert:
      tableView.insertRows(at: [newIndexPath!], with: .fade)
    case .delete:
      tableView.deleteRows(at: [indexPath!], with: .fade)
    case .update:
      tableView.reloadRows(at: [indexPath!], with: .fade)
    case .move:
      tableView.moveRow(at: indexPath!, to: newIndexPath!)
    }
  }

  func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    tableView.endUpdates()
  }
}

新尝试

在回复评论时,我添加了NSFetchedResultsControllerDelegate实施,这是Apple在文档中列出的内容。我注意到有强制解包可选项,因此我抛出了一些guard语句,我关闭动画以获得良好的衡量标准。我在同一个地方也做同样的事情。

这是更新的委托方法,添加了保护语句并关闭了动画:

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

    guard let indexPath = indexPath else { return }

    switch type {
    case .insert:
      guard let newIndexPath = newIndexPath else { return }
      tableView.insertRows(at: [newIndexPath], with: .none)
    case .delete:
      tableView.deleteRows(at: [indexPath], with: .none)
    case .update:
      tableView.reloadRows(at: [indexPath], with: .none)
    case .move:
      guard let newIndexPath = newIndexPath else { return }
      tableView.moveRow(at: indexPath, to: newIndexPath)
    }
  }

更新2

在回复评论时,这是我用来更新谓词的代码。我有观察员startDate&amp;调用endDate的{​​{1}}。按下updatePredicate()时会更新startDateendDate。:

segmentedControl

这是fetchResults():

  // This is used to set values for searching via segmentedControl
  @objc dynamic var startDate: Date?
  @objc dynamic var endDate: Date?

  func updatePredicate() {
    // you need a start date or stop executing
    guard let startDate = startDate else { return }

    var predicateArray: [NSPredicate] = []

    if let endDate = endDate {
      let startEndPredicate = NSPredicate(format: "time >= %@ AND time <= %@", argumentArray: [startDate, endDate])
      predicateArray.append(startEndPredicate)
    } else {
      // use the startDate's end of day if endDate is nil
      let startPredicate = NSPredicate(format: "time >= %@ AND time <= %@", argumentArray: [startDate, startDate.endOfDay!])
      predicateArray.append(startPredicate)
    }

    let sliderPredicate = NSPredicate(format: "magnitude >= %f", argumentArray: [magSlider.value])
    predicateArray.append(sliderPredicate)

    currentPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicateArray)

    fetchResults()
  }

更新3

在回应另一条评论时,以下是FRC声明:

  func fetchResults() {
    do {
      fetchedResultsController.fetchRequest.fetchBatchSize = 35
      fetchedResultsController.fetchRequest.fetchLimit = 1_000
      try fetchedResultsController.performFetch()
    } catch let error {
      print("\(error) \(error.localizedDescription)")
    }
    DispatchQueue.main.async {
      self.tableView.reloadData()
      self.tableView.setContentOffset(.zero, animated: true)
      self.updateLabelsForResults()
    }
  }

2 个答案:

答案 0 :(得分:2)

我最终玩fetchLimit,这似乎解决了我的问题。

当我执行提取时,我按如下方式使用它:

fetchedResultsController.fetchRequest.fetchLimit = 2_500

2,500的大小与我在不崩溃应用程序的情况下一样大。

答案 1 :(得分:0)

当FRC与fetchBatchSize一起使用时,FRC运行的数据集是代理阵列。如果在访问批处理元素时尚未提取批处理数据,则会在访问时提取该数据。

代理服务器阵列的线程安全性与您操作的管理对象的线程安全性相同 - 必须从基础MOC的专用队列访问它。您可以在本文后面检查线程安全性是否存在问题:https://oleb.net/blog/2014/06/core-data-concurrency-debugging/。理想情况下,访问必须采用这种方式:

var myObject;
fetchedResultsController.managedObjectContext.performBlockAndWait({
    myObject = fetchedResultsController.object(at: indexPath) 
})
cell.myObject = myObject

此外,在崩溃时请检查这些陈述是否属实:

1) fetchedResultsController.sections.first.numberOfObjects <= 
                                         fetchedResultsController.fetchRequest.fetchLimit

2) fetchedResultsController.sections.first.numberOfObjects == 
                                         tableView.numberOfRows(inSection: 0)

如果1)不成立 - FRC不尊重fetchLimit,只应使用fetchBatchSize

如果2)不成立 - 这意味着当更改FRC数据集时tableView没有得到适当更新。需要进一步调试以确定原因。

相关问题