0

Всем привет!!

Есть модель в кор дате, при самом первом запуску соответсвенно она пустая. Данные из модели должны подгружаться в tableview с помощью nsfetchedresultcontroller.

Получаю json, парсю его, сохраняю в бд.

Но таблица не обновляется.(данные в кор дате есть)

Вылезает ошибка(прикрепил снизу), в принципе из ее текста причина понятна, то что кол-во секций почему-то не обновляется.

При последующем запуске приложения, таблица отображает все данные.

Долго сижу уже с ней, подскажите в какую сторону смотреть.

Ошибка *** Assertion failure in -[UITableView _endCellAnimationsWithContext:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3698.54.4/UITableView.m:1993

[error] error: Serious application error. An exception was caught from the delegate of NSFetchedResultsController during a call to -controllerDidChangeContent:. Invalid update: invalid number of sections. The number of sections contained in the table view after the update (2) must be equal to the number of sections contained in the table view before the update (0), plus or minus the number of sections inserted or deleted (0 inserted, 0 deleted). with userInfo (null)

class ScheduleDataConfig: NSObject, NSFetchedResultsControllerDelegate {

let fetchedResultsController: NSFetchedResultsController<ScheduleOfSpecificGroup>
let tableView: UITableView

init(tableView: UITableView, groupId: String) {
    self.tableView = tableView

    let fetchRequest: NSFetchRequest<ScheduleOfSpecificGroup> = ScheduleOfSpecificGroup.fetchRequest()

    fetchRequest.predicate = NSPredicate(format: "group == %@", groupId)

    fetchRequest.sortDescriptors = [
        NSSortDescriptor(key: "group", ascending: false),

    ]

    fetchedResultsController =  NSFetchedResultsController<ScheduleOfSpecificGroup>(fetchRequest: fetchRequest, managedObjectContext : CoreDataStack.sharedCoreDataStack.mainContext!, sectionNameKeyPath: nil, cacheName : nil)
    super.init() /////////////
    fetchedResultsController.delegate = self
    do {
        try  self.fetchedResultsController.performFetch()
    } catch  {
        print(error)
    }
}



func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {

    tableView.beginUpdates()

}

func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {

    tableView.endUpdates()
}

func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange  anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
    switch type {
    case .delete:
        if let indexPath = indexPath {
            tableView.deleteRows(at: [indexPath], with: .automatic)
        }
    case .insert:
        if let newIndexPath = newIndexPath {

            tableView.insertRows(at: [newIndexPath], with: .automatic)

        }
    case .move:
        if let indexPath = indexPath {
            tableView.deleteRows(at: [indexPath], with: .automatic)
        }
        if let newIndexPath = newIndexPath {
            tableView.insertRows(at: [newIndexPath], with: .automatic)
        }
    case .update:
        if let indexPath = indexPath {

            tableView.reloadRows(at: [indexPath], with: .automatic)

        }
    }
}

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

}

0

1 ответ 1

1

Непонятно, по какому принципу у вас вообще идёт деление на секции, если вы в параметр sectionNameKeyPath у конструктора NSFetchedResultsController подаёте nil.

Кроме того, число секций неизвестно таблице, поскольку метод numberOfSections(in:) протокола UITableViewDataSource не имплементирован. Также неизвестно и число ячеек в секции (tableView(_:numberOfRowsInSection:)) и метод их получения и заполнения.

Если эти методы и определены в другом классе, то непонятно, как этот другой класс получает доступ к текущему NSFetchedResultsController и как с ним работает – а для ответа на вопрос это важно.

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.