Search code examples
iosswiftcore-datansfetchedresultscontroller

Core Data fetch request one-to-many relationships with NSFetchedResultsController


If I have several entities lets say Genre, Artist, Song and there is a relationship between the three One-To-Many, how I go about searching artists within the Genre, given that I have a generic NSFetchedResultsController, that is in my CoreManager class that my tableviews conforms. The code works fine to request the content of the entity but I am not sure if I tapped on one of the Genres to display those artists within them and go to multiple levels. My FRC code is

fetchedResultsController = {
    let request = fetchRequest
    request.sortDescriptors = sortDescriptor
    request.predicate = fetchPredicate
    request.returnsObjectsAsFaults = false
    let context = managedContext
    let frc = NSFetchedResultsController(
        fetchRequest: fetchRequest,
        managedObjectContext: context,
        sectionNameKeyPath: sectionNameKeyPath , cacheName: cacheName)
    return frc
}()

enter image description here


Solution

  • If you want your FRC to filter Artists by Genre, you will need to add a relationship from Artist to Genre (the inverse of the artists relationship on the Genre entity). As a side note, you should almost always define an inverse for every relationship - there are very few situations where you are better off without an inverse.

    I'm not sure whether you would regard each Artist as having only one Genre, or possibly having many - set the relationship as to-one or to-many as appropriate, and name it genre or genres accordingly. The predicate that is then required will be different in each case:

    For to-one, you should use

    NSPredicate(format:"genre == %@", chosenGenre)
    

    and for to-many you would use

    NSPredicate(format:"ANY genres == %@", chosenGenre)
    

    (assuming you already have a reference, chosenGenre, to the genre you wish to filter by. If you in fact have only the genre title, you would use:

    NSPredicate(format:"genre.title == %@", chosenGenreTitle)
    

    and for to-many you would use

    NSPredicate(format:"ANY genres.title == %@", chosenGenreTitle)