3

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!
        )
    }
Michał Ziobro
  • 10,759
  • 11
  • 88
  • 143
  • Does this answer your question? [SwiftUI View and @FetchRequest predicate with variable that can change](https://stackoverflow.com/questions/57871088/swiftui-view-and-fetchrequest-predicate-with-variable-that-can-change) – gotnull Dec 10 '19 at 00:10
  • No answers there doesn't work code doesn't compile accessing Binding. @FetchRequest seems to be useless if you cannot change predicates sorting based on View state. – Michał Ziobro Dec 10 '19 at 09:20

0 Answers0