Sort CoreData results using NSPredicate in Swift

后端 未结 2 458
抹茶落季
抹茶落季 2021-01-01 23:56

I\'m currently writing a simple phone book app in Swift and need to sort the results from a CoreData query.

Basically, I set up an NSManagedObject called \"Directory

相关标签:
2条回答
  • 2021-01-02 00:42

    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 )
    }
    
    0 讨论(0)
  • 2021-01-02 00:57

    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
    
    0 讨论(0)
提交回复
热议问题