From 5dad79ef9ba324c20c8d62bb73907e4f00dc5560 Mon Sep 17 00:00:00 2001 From: Sophia Liu <91706701+s0phialiu@users.noreply.github.com> Date: Wed, 21 Feb 2024 13:14:23 -0600 Subject: [PATCH] fixed issue where the schedule page may crash after favoriting > 1 event (#581) --- .../HIEventListViewController.swift | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/HackIllinois/ViewControllers/HIEventListViewController.swift b/HackIllinois/ViewControllers/HIEventListViewController.swift index 7adfb631..c57c0311 100644 --- a/HackIllinois/ViewControllers/HIEventListViewController.swift +++ b/HackIllinois/ViewControllers/HIEventListViewController.swift @@ -71,10 +71,20 @@ extension HIEventListViewController { // MARK: - HIEventCellDelegate extension HIEventListViewController: HIEventCellDelegate { + // This method is necessary to refresh the indecies and sections in the table view controller + func fetchAndReloadData() { + try? _fetchedResultsController?.performFetch() + tableView?.reloadData() + } + func eventCellDidSelectFavoriteButton(_ eventCell: HIEventCell) { - guard let indexPath = eventCell.indexPath, - let event = _fetchedResultsController?.object(at: indexPath) as? Event else { return } - + guard let indexPath = eventCell.indexPath else { return } + // Ensure the section and item indices are within bounds + guard indexPath.section < _fetchedResultsController?.sections?.count ?? 0, + indexPath.item < _fetchedResultsController?.sections?[indexPath.section].numberOfObjects ?? 0 else { + return + } + guard let event = _fetchedResultsController?.object(at: indexPath) as? Event else { return } guard let user = HIApplicationStateController.shared.user else { return } let changeFavoriteStatusRequest: APIRequest = @@ -93,6 +103,8 @@ extension HIEventListViewController: HIEventCellDelegate { } else { HILocalNotificationController.shared.unscheduleNotification(for: event) } + // Call the fetchAndReloadData method to update the fetched results controller and reload the table view, otherwise index and section of next events will be incorrect + self.fetchAndReloadData() } case .failure(let error): print(error, error.localizedDescription)