Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12111

How to fetch SectionedFetchRequest with the relationship object as its section id

$
0
0

There are two entities in my app, 'Card' and 'CardRecord', they have 1:n relationship, one card has many records. I have a view that needs to show how many records are there in each card, so here is my code:

@SectionedFetchRequestprivate var sectionRecords: SectionedFetchResults<Card, CardRecord>init(month: Int32) {    let predicate = NSPredicate(format: "month = %i", month)    _sectionRecords = SectionedFetchRequest<Card, CardRecord>(        entity: CardRecord.entity(),        sectionIdentifier: \CardRecord.card!,        sortDescriptors: [],        predicate: predicate    )}var body: some View {    VStack(alignment: .leading) {        ForEach(sectionRecords) { section in            CardExpansionView(card: section.id, num: Int32(section.count))        }    }}

I only need to loop the sectionRecords because I only need the number of each section, and I need show the @ObservedObject Card, that's why I use the relationship object Card as the section id.

When I run the app in a simulator, an error occurred:

ForEach<SectionedFetchResults<Card, CardRecord>, Card, CardExpansionView>: the ID <Card: 0x6000025fdf40> (entity: Card; id: 0xe565b4b98e84a111 <x-coredata://292B0160-058F-48AE-BFCC-11196BF00552/Card/p24>; data: {    cid = "6E3C25B7-2DC2-4538-B3D9-950A387C13AD";    color = CardBrown;    createTime = "2024-04-04 07:47:22 +0000";    icon = "cup.and.saucer";    name = "NO COFFEE";    records = "<relationship fault: 0x60000063f6e0 'records'>";}) occurs multiple times within the collection, this will give undefined results!

At the same time another question arises, the number of sections shown on the page is not correct and there are duplicate cards.

Then I add an attribute 'cardId' in the entity 'CardRecord' and change the sectionid to cardId

sectionIdentifier: \CardRecord.cardId!

When I run the app again... The error is gone, but the number of sections is still wrong and duplicates are still exist.

So, what is the problem and what do I need to do about it.

And finally, a question: how to sort the 'sectionRecords' by the 'section.count'

And thanks.


Viewing all articles
Browse latest Browse all 12111

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>