WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

List, NSFetchedResultsController, Sections

Forums > SwiftUI

Dear all,

I would like to know how you handle Sections in a List in SwiftUI when you use an NSFetchedResultsController. In the config of the NSFetchedResultsController there is a sectionNameKeyPath but I don't think you can adress this somehow in SwiftUI like you can in UKit.

Currently, I use a function to get the sections titles in my list and filter my results for the section in the second loop.

List(viewModel.filterSections(), id:\.self) { section in
  Section(header: Text(section)) {
      ForEach(viewModel.filterFood(for: section)) { food in
        Text(food.foodname!)
      }
  }
}

filterSections returns just a [String].

So how do you handle this case?

1      

Here's one way to get it to work. This uses a simple model with one entity, Item, that has two String properties: title and section.

@main
struct CoreDataTestsApp: App {
    let persistenceController = PersistenceController.shared

    var body: some Scene {
        WindowGroup {
            ContentView(context: persistenceController.container.viewContext)
        }
    }
}

class ContentViewModel: NSObject, ObservableObject, NSFetchedResultsControllerDelegate {
    @Published var sections: [NSFetchedResultsSectionInfo] = []

    let itemController: NSFetchedResultsController<Item>

    init(context: NSManagedObjectContext) {
        let request = NSFetchRequest<Item>(entityName: "Item")
        request.sortDescriptors = [
            NSSortDescriptor(keyPath: \Item.section, ascending: true)
        ]
        //it's important that the keyPath of the first sort descriptor 
        //  matches the property you use for sectionNameKeyPath 
        //  when building the NSFetchedResultsController
        //you'll get weird results otherwise

        itemController = NSFetchedResultsController(
            fetchRequest: request,
            managedObjectContext: context,
            sectionNameKeyPath: #keyPath(Item.section),
            cacheName: nil
        )

        super.init()
        itemController.delegate = self

        do {
            try itemController.performFetch()
            sections = itemController.sections ?? []
        } catch {
            print("failed to fetch items")
        }

    }

    func sectionItems() -> [String: [Item]] {
        (itemController.sections?.reduce(into: [String: [Item]]()) { dict, section in
            dict[section.name] = section.objects as? [Item] ?? []
        }) ?? [:]
    }

    func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
        sections = itemController.sections ?? []
    }
}

struct ContentView: View {
    @StateObject var viewModel: ContentViewModel
    let context: NSManagedObjectContext

    init(context: NSManagedObjectContext) {
        let viewModel = ContentViewModel(context: context)
        _viewModel = StateObject(wrappedValue: viewModel)
        self.context = context
    }

    var body: some View {
        NavigationView {
            List {
                ForEach(viewModel.sections, id: \.name) { section in
                    Section(header: Text(section.name)) {
                        ForEach(section.objects as? [Item] ?? [], id: \.title) { item in
                            Text(item.title ?? "---")
                        }
                        .onDelete { row in
                            deleteItem(section: section, row: row)
                        }
                    }
                }
            }
            .toolbar {
                Button(action: addItem) {
                    Label("Add Item", systemImage: "plus")
                }
            }
        }
    }

    private func addItem() {
        withAnimation {
            let newItem = Item(context: context)
            newItem.title = "Fallon"
            newItem.section = "Women"

            do {
                try context.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nsError = error as NSError
                fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
            }
        }
    }

    private func deleteItem(section: NSFetchedResultsSectionInfo, row: IndexSet) {
        if let itemRow = row.first,
           let itemToDelete = section.objects?[itemRow] as? Item {
            context.delete(itemToDelete)
            do {
                try context.save()
            } catch {
                let nsError = error as NSError
                fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
            }
        }
    }
}

Edit: My original solution didn't work so well when adding and deleting items. Not sure why, but I think it had to do with using a Dictionary in the ForEach. Anyway, here's an updated solution that doesn't crash when adding/deleting.

2      

Hi @roosterboy, thank you for your suggestion. The solutions works. What I found is it seems a little slower than my solution. Currently, I have over 1000 items and there is a slighly longer delay in presenting the list. I will come back to you and will report after I tested more than I thought my approach is more time consuming.

Additionally, I added searching with searchable which I wasn't able to get working in your code.

My ViewModel looks almost the same as yours besides the names and the types. These are my functions to get the data back to my view:

func filterSections() -> [String] {
    if searchText.isEmpty {
        return foodController.sectionIndexTitles
    } else {
        var sections = [String]()
        sections = food.filter({ $0.foodname!.contains(searchText)}).map{ $0.sortSection ?? "" }.removingDuplicates()
        return sections
    }
}

func filterFood(for section: String) -> [RNFood] {
    if searchText.isEmpty {
        return food.filter{ $0.sortSection == section } 
    } else {
        return food.filter{ $0.sortSection == section && $0.foodname!.contains(searchText)}
    }
}

1      

Thank you again for your help, @roosterboy.

I stayed with my solutions for now because I was struggling to implement the search bar with your solution. Speed wise there was no measurable difference with my amount of data.

1      

Hacking with Swift is sponsored by RevenueCat

SPONSORED You know StoreKit, but you don’t want to do StoreKit. RevenueCat makes it easy to deploy, manage, and analyze in-app subscriptions on iOS and Android so you can focus on building your app.

Explore the docs

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.