Cris Denopol
Cris Denopol

Reputation: 322

How to get sectioned data from a CoreData entity relationship in Swift

enter image description here

I have a one to many relationship User -> Weight as shown on the screenshot. I am able to extract sectioned data from an entity using NSFetchRequest and NSFetchedResultsController and then show it on a Table view with sections.

I am able to extract weight data via the User entity. But my question is, how do I extract that weight data such that I could display it on a table view with sections similar to how NSFetchedResultsController does?

Any help would be appreciated. Thanks in advance!

Upvotes: 0

Views: 75

Answers (2)

Cris Denopol
Cris Denopol

Reputation: 322

Ok, so I figured out the best approach to this. Instead of getting the weight data by querying the User entity, I queried the Weight entity instead and used a predicate to return only the weight data of a specific user.

Something like this:

func requestFetch(ofUser selectedUser: User) -> NSFetchRequest{ ... let userPredicate = NSPredicate(format: "user == %@", selectedUser) ... return fetchRequest }

Upvotes: 0

Jon Rose
Jon Rose

Reputation: 8563

A NSFetchedResultsController can interact with a collectionView or tableView with its objectAtIndexPath and sections property. But you don't need to use it that way. You can create a NSFetchedResultsController on just the User objects with no sectionNameKeyPath. The number of sections is the the fetchedResultsController number of items. And the number of items in each section is equal to each items's number of weights. likewise when you get the delegated callbacks for changes convert the fetchedResultsController's indexPaths to sections.

Upvotes: 1

Related Questions