CA Bearsfan
CA Bearsfan

Reputation: 474

Using NSFetchedResultsController to fetch an object's property

I need to make a CoreData fetch request that grabs a ManagedObject of type "List" which properties include: name(String), hitCount(Int), lastUpdated(Date) and contents(OrderedSet). Now I need to populate my TableView with the "Media" ManagedObjects within the contents property of the List Object. When I already have an instance of the List who's contents I want I've tried...

let fetchRequest = NSFetchRequest<Media>(entityName: "Media")
fetchRequest.predicate = NSPredicate(format: "SELF in %@", list.contents)

...which gives me what is already in CoreData, but not any NSFetchedResultsControllerDelegate updates on additional objects obtained through network calls and added to the database after my initial grab. I also tried...

let fetchRequest = NSFetchRequest<Media>(entityName: "List")
fetchRequest.predicate = NSPredicate(format: "name == %@", list.name)

...which returns the List item and I will get NSFetchedResultsControllerDelegate updates, but only of type move on the List object itself - not the actual changes needed to apply to the TableView (delete/insert,etc) when it's content property changes. Is there a way to achieve what I'm trying to do? Any help is greatly appreciated.

Upvotes: 1

Views: 619

Answers (1)

pbasdf
pbasdf

Reputation: 21536

If the inverse relationship is to-one, called listRelationship, then you can use:

let fetchRequest = NSFetchRequest<Media>(entityName: "Media")
fetchRequest.predicate = NSPredicate(format: "listRelationship == %@", list)

as the fetch underlying the FetchedResultsController. If the relationship is to-many, change the predicate to "ANY listRelationship == %@". In either case, it will be difficult to ensure the sort order used by the FRC matches the NSOrderedSet in the List object.

If that is important to you, you will need to explicitly model the sort order with an index attribute. If the relationship is to-one, you can add the index attribute to the Media entity, but if it is to-many, life gets more difficult: a Media object might be the first item in one List, but the last item in another List - so the index relates to a particular List and a particular Media item. In that case, add another entity, "ListEntry", with an index attribute and to-one relationships to List and Media (each with to-many inverses).

Upvotes: 3

Related Questions