1

Following How to limit the number of results in a FetchRequest in SwiftUI I created a FetchRequest to get the latest billing number.

My code looks like this

var billNo: FetchRequest<Payments>
...
init() {
    let request: NSFetchRequest<Payments> = Payments.fetchRequest()
    request.fetchLimit = 1
    request.sortDescriptors = [NSSortDescriptor(key: "rechnungsNummer", ascending: false)]
    billNo = FetchRequest<Payments>(fetchRequest: request)
}

But how on earth do I get access to the values of billNo.rechnungsNummer? billNo.wrappedValue.first?.rechnungsNummer ist always nil.

Or has it all changed the last two years?

btw: it's all inside a view. ;)

mihema
  • 158
  • 1
  • 10
  • changes in `request.sortDescriptors = [NSSortDescriptor(keyPath: \Payments.rechnungsNummer, ascending: false)]`doesn't make it better. – mihema Jul 23 '22 at 14:40
  • 1
    You have to call `fetch` on the managed object context to get the results. – vadian Jul 23 '22 at 14:46

1 Answers1

1

Thanks to vadian for the missing hint.

Here's my working code:

@FetchRequest var billNo: FetchedResults<Payments>
...
init() {
    let request: NSFetchRequest<Payments> = Payments.fetchRequest()
    request.fetchLimit = 1
    request.sortDescriptors = [NSSortDescriptor(key: "rechnungsNummer", ascending: false)]
    _billNo = FetchRequest<Payments>(fetchRequest: request)
}

And in body, I can access this easily with

billNo.first?.rechnungsNummer

I hope it might help other beginners like me. :-)

mihema
  • 158
  • 1
  • 10