SwiftUI using instance variable in @FetchRequest

Viewed 184

I am trying to use a instance variable in my FetchRequest. I do understand that I can not use the instance variable as my init hasn't been called yet.

I tried doing my FetchRequest in the init instead, which works, however isn't updated when the data changes. Is there a chance to use @FetchRequest which updates automatically, and using my instance variable?

I can not declare @FetchRequest inside the init. Any other solution?

That is my @FetchRequest

@FetchRequest(entity: PersonVenueMapping.entity(), sortDescriptors: [NSSortDescriptor(key:"", ascending: true)], predicate: NSPredicate(format: "person == %@", PersonFormVenues.personStatic!)) var test123: FetchedResults<PersonVenueMapping>

I am using person as instance variable. That's why I am getting the error.

That is my code in the init:

//Declaration
var personVenueMapping = [PersonVenueMapping]()

let sortDescriptor = NSSortDescriptor(key: "", ascending: true)

var test : NSFetchRequest<PersonVenueMapping> = PersonVenueMapping.fetchRequest()
test.predicate = NSPredicate(format: "person == %@", person)

do {
    self.personVenueMapping = try NSManagedObjectContext.current.fetch(test)
} catch
{
}

I thought of using @State for my personVenueMapping, however setting the initial data didn't work correctly either.

TL:DR: I want the functionality of @FetchRequest, and still use my instance variable.

0 Answers
Related