Kyle Arcilla
Kyle Arcilla

Reputation: 29

CORE Data: Fetching Objects in Accordance to Their Relationships

I am currently experimenting with CORE Data and I am trying to fetch request a core data in accordance with their parent relationship. I have two entities, I have a task entity (relationship: task.category) and a category (relationship: category.tasks).

I am currently having trouble fetching tasks in accordance to their parent category relationships.

struct CategoryCard 

    @Environment(\.managedObjectContext)
    var context: NSManagedObjectContext
    
var predicate : String
var category : Category!       // 1. Category is Passed in

@FetchRequest(entity: Task.entity(), sortDescriptors: [NSSortDescriptor(key: "date", ascending: true)],
              predicate: NSPredicate(format: "task.parentCategory == %@", category.title!),
              animation: .spring()
)

var results : FetchRequest<Task>

I am currently getting the error: Cannot use instance member 'category' within property initializer; property initializers run before 'self' is available

I am also trying to display these results with a ForEach loop.

ForEach(results, id: \.self) { task in
                        Text("\(task)")  
                    }

Also, this Card View struct is called using a ForEach Loop from a different file.

ForEach(categoriesResults, id: \.self) { category in
                        CategoryBoxView(category: category)
 }

How should I go about approaching this problem?

Upvotes: 0

Views: 45

Answers (1)

Joakim Danielson
Joakim Danielson

Reputation: 51882

Access the tasks from the category that is passed in, you don't need a fetch request or a property for the tasks

ForEach(self.category.tasks, id: \.self) { task in
    Text("\(task)")  
}

Upvotes: 1

Related Questions