0

There are many similar questions, especially for Objective C, but I have not been able to figure out how to apply it to my project in Swift using Core Data.

  • I have two entities List and Tasks
  • Inverse one-to-many relationship between them, one list can have many tasks

What I want to do is simple. I want to fetch tasks belonging to SPECIFIC List using one-to-many relationship between these entities. I can fetch all Tasks, and all Lists, there is plenty of coverage on that. But I can not fetch JUST tasks belonging to specific list.

My most recent attempts goes like this:

ATTEMPT 1

  1. Based on the name of the selected list I use NSPredicate to get that specific list
let listFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "List") 


listFetchRequest.predicate = NSPredicate(format: "name = %@", selectedList.value(forKeyPath: "name") as! String
  1. List Entity has only 1 attribute name, and "tasks" relationship to Task entity. What I want to do is use this "tasks" relationship to fetch ONLY tasks that belong to this specific list.
    let tasksSet = selectedList.tasks

This for example returns NSOrderedSet that I do not know how to convert to Task custom object. I tried

let tasksSet = selectedList.tasks?.objectEnumerator()

, but still can not get the Task object that I need.

ATTEMPT 2

Here I try the other way around, to fetch all of the Tasks directly, and then filter tasks for the selectedList using one-to-many inverse relationship named "list" and located in Task entity.

let tasksFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Task")
tasksFetchRequest.predicate = NSPredicate(format: "list = %@", selectedList)

Although this question may be flagged as repeating, I have read through many answers, 2 books and many online tutorials (that tell you only this is how you create Entity, this is how you add attribute and all of the simple stuff, but no good coverage on NSPredicate, subqueries, not mentioning how to fetch relationships etc), but am not able to make this simple query.

Thanks

Bosniak
  • 29
  • 7
  • Or does this answer your question? [How to covert NSMutableOrderedSet to generic array?](https://stackoverflow.com/questions/27076811/how-to-covert-nsmutableorderedset-to-generic-array) – Willeke Feb 07 '20 at 02:21
  • Thank you so much. I converted OrderedSet to generic array, and had the data I need. Thanks! – Bosniak Feb 11 '20 at 15:32

0 Answers0