0

I am using NSFetchedResultsController to display data in a table view. I have 2 objects, Client, and Formula. A Client can have many Formulas but a Formula can have just one Client, so a one-to-many relationship. When I tap on a certain Client in a table view cell, I want to only be seeing formulas related to that client, but when I tap on other cells, those contain the same Formula objects, so it's not filtering. I know I need to use a predicate to filter the fetch request, but I do not know where to start.

This is the fetchedResultsController I have set up.

let fetchedResultsController: NSFetchedResultsController<Formula> = {
    let fetchRequest: NSFetchRequest<Formula> = Formula.fetchRequest()
    let sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)]
    fetchRequest.sortDescriptors = sortDescriptors

    return NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: CoreDataStack.context, sectionNameKeyPath: "date", cacheName: nil)
}()

So somewhere in there, I have to add fetchRequest.predicate = NSPredicate(format: ...) but I do not know what to enter inside that initializer.

  • `format: "theAttributeOfFormulaThatLinksItToAClient.anAttributedOfClientThatCanIdentifiyIt == %@", theClientSelectedIDValueThatCanIdentifyIt`. We need to see your model, but that's more or less what to do. – Larme Jul 28 '17 at 06:02
  • My model is a .datamodeld file – Garret Koontz Jul 31 '17 at 03:58
  • @Larme This is what I've tried: `let predicate = NSPredicate(format: "client.formulas == %@", CVARARG)` . I don't know what to put for the CVarArg. – Garret Koontz Jul 31 '17 at 04:06

1 Answers1

0

As you have mentioned in your question, you need to add a predicate to your fetch request to filter the fetched objects. In that predicate you need to use reverse relationship from Formula to Client. Like so:

fetchRequest.predicate = NSPredicate(format: "parentClient == %@", parentClient)
Luke
  • 965
  • 8
  • 21