New SwiftUI property wrapper of @FetchRequest is very nice tool but it has important limitation I think. It can be used with some static content. But If I want do make such request based on state of some other var it seems to be not so easy to implement
@UserDefault(UserDefaultKey.UserId, defaultValue: "")
var userId: String
@FetchRequest(
entity: Company.entity(),
sortDescriptors: [
NSSortDescriptor(keyPath: \User.email, ascending: true)
],
predicate: NSPredicate(format: "id == %@", self.userId)
)
var user: FetchedResults<User>
Above code sample doesn't compile as it result in error:
Use of unresolved identifier 'self'
The only way to workaround it as I know is to write init() and inject userId into it but this makes all process of fetching database results not so fun.
Also something like this doesn't work. And having to pass userId to one component to then get user to pass relationship id to another view component seems very cumbersome
init() {
var predicate: NSPredicate = NSPredicate(format: "id == %@", self.settings.userId)
self._fetchRequest = FetchRequest(
entity: Company.entity(),
sortDescriptors: [
NSSortDescriptor(keyPath: \User.email, ascending: true)
],
predicate: predicate!
)
}