Sort CoreData results using NSPredicate in Swift
Thanks - The following lines were required before the request.predicate line:
let sortDescriptor = NSSortDescriptor(key: "name_f", ascending: true)let sortDescriptors = [sortDescriptor]request.sortDescriptors = sortDescriptors
I used the above answer from Oliver Spencer, because the sorting approach includes pending changes, which the "max" approach dose not (see apple documentation on NSFetchRequest).
Here my code for convenience:
func fetch_biggestImageID() -> Int { print("Fetching biggest ImageID") let request: NSFetchRequest<CD_Image> = CD_Image.fetchRequest() request.sortDescriptors = [NSSortDescriptor(key: "id", ascending: false)] request.fetchLimit = 1 var maxValue: Int64? = nil do { let result = try self.managedObjectContext.fetch(request) maxValue = result.first?.id } catch { fatalError("Unresolved error while retrieving max imageID value \(error)") } return Int(truncatingIfNeeded: maxValue ?? 0 )}