mink23
mink23

Reputation: 154

Multiple Fetch Requests?

I currently have a UITableView with 2 sections that uses a NSFetchedResultsController. I am trying to work out how I display different entities in the different sections. I have a FOLDER objects and then also TAG objects. I am wanting to display all of these in each section, i.e. Section 1 all FOLDER, Section 2 all TAGS.

The relationship goes: FOLDER (one to many)-> MOVIE (many to many)-> TAGS

How do I achieve this? Am I needing 2 separate tableView's or to use a single tableView with 2 different fetch requests? Please help!

EDIT: Fetch and tableView cellForRowAt code.

  private let appDelegate = UIApplication.shared.delegate as! AppDelegate
   private let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
   private var fetchedRC: NSFetchedResultsController<Folder>!

   override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    refresh()
   }

   private func refresh() {
    do {
        let request = Folder.fetchRequest() as NSFetchRequest<Folder>
        request.predicate = NSPredicate(format: "name CONTAINS[cd] %@", query)
        let sort = NSSortDescriptor(keyPath: \Folder.name, ascending: true)
        request.sortDescriptors = [sort]
        do {
            fetchedRC = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
            fetchedRC.delegate = self
            try fetchedRC.performFetch()
        } catch let error as NSError {
            print("Could not fetch. \(error), \(error.userInfo)")
        }
    }
   }

   func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "folderCell", for: indexPath) as! FolderTableViewCell
    let folder = fetchedRC.object(at: indexPath)
    cell.update(with: folder)
    cell.layer.cornerRadius = 8
    cell.layer.masksToBounds = true
    return cell
   }

Upvotes: 1

Views: 356

Answers (1)

MartinM
MartinM

Reputation: 937

Use 2 FRC for your 2 sections.

One gets fed by your folder fetchrequest and the other by the tags, all in one tableview. Your tableview delegate methods take care of what you want to access. This is quite easy to handle that way. It only gets more complicated if you have more than just 2 sections. That way your tableview delegate knows by section == 0 or 1 which FRC to access.

Upvotes: 2

Related Questions