0

I have 2 important entities in CoreData: 1) generic products (Item_general) and 2) occurrence of a product, that user customized and put to his cart (Repository_item).

I want to display to the user list of products that user added, however it must be grouped by generic product and displayed all together in one view. Additionally, products must be filtered by category (Item_category) So I believe, I need to group results in a view using SectionedFetchRequest, and put the category as predicate.

This code below is part of the view and does not work because of error:

Cannot use instance member 'itemCategorySet' within property initializer; property initializers run before 'self' is available

@SectionedFetchRequest<Item_general,Repository_item>(
    sectionIdentifier: \Repository_item.item_occurrence!.item_general!,
    sortDescriptors: [],
    predicate: NSPredicate(format: "Repository_item.item_occurrence.item_general.item_category.guid = %@", itemCategorySet.guid!.description)
)
private var sectionedItems: SectionedFetchResults<Item_general,Repository_item>
var itemCategorySet: Item_category

So I tried a different approach and moved the query to persistence controller. And this code below has error:

Cannot convert value of type 'SectionedFetchRequest<Item_general, Repository_item>' to expected argument type 'NSFetchRequest'"

func getItemGeneralByCategory(guid: UUID!) -> SectionedFetchResults<Item_general,Repository_item>.Element? {
    let fetchRequest = SectionedFetchRequest<Item_general,Repository_item>(sectionIdentifier: \Repository_item.item_occurrence!.item!, sortDescriptors: [], predicate: NSPredicate(format: "item_occurrence.item.category.guid = %@,", guid.description))

    // Get a reference to a NSManagedObjectContext
    let context = container.viewContext
    if let objects = try? context.fetch(fetchRequest) {
        return objects
    }
}

Is there a way to read the data directly in the view (first method)?

If not, how should I read data from SectionedFetchRequest in persistanceController?

soundflix
  • 928
  • 9
  • 22
Kamil Sko
  • 1
  • 4
  • does this answer your question: https://stackoverflow.com/questions/57871088/swiftui-view-and-fetchrequest-predicate-with-variable-that-can-change – workingdog support Ukraine Aug 20 '23 at 01:27
  • Great, thank you! it is building. I have to fix couple of other issues and will report here the final code. – Kamil Sko Aug 20 '23 at 08:23
  • It works quite similarly as with FetchRequest, I was amazed that you don't have to execute the query, but SwiftUI does it automatically. Just the declared type had to be `private var sectionedItems: SectionedFetchResults{sectionedFetchRequest.wrappedValue}` – Kamil Sko Aug 20 '23 at 13:01

0 Answers0