Search code examples
swiftcore-datarelationshipnsfetchedresultscontroller

Core data: NSFetchedResultsController with objects are in a relationship


I have two entities CIDMPost and CIDMUser. CIDMPost has a one-to-many relationship with CIDMUser named invitees. Now I have an instance of CIDMPost lets say postObject from where I can easily get the invitees by writing postObject.invitees which will return NSSet.

Now my requirement is I want those invitees (postObject.invitees) as NSFetchedResultsController to show in a UITableView with style Group. Also its need to satisfy the below.

  1. Grouped by invitationStatus (an attribute of CIDMUser)
  2. Order by invitationStatus ASC

Declaration:

I tried few things to fulfil my requirement but got a crashed and the reason was Invalid to many relationship. To know the solution of this crash I posted 'a question' an hour ago. But after few conversation with Daij-Djan I had come to know that the whole process I was trying is wrong.


Solution

  • Just fetch the users in your fetched results controller and apply the sort descriptors as desired filter by invitation with a predicate. Use the status field as the sectionNameKeyPath argument when creating the fetched results controller.

    NSPredicate(format: "%@ in invitations", post)
    

    where post is the post object to which you want to display the invitees, and invitations is the reverse to-many relationship to the post to which users are invited.

    (Note that I am assuming a user can get invited to more than one post, which seems logical. In your problem statement you mention a one-to-many relationship which it seems to me should thus be many-to-many).