Sort CoreData results using NSPredicate in Swift

后端 未结 2 475
抹茶落季
抹茶落季 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.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 )
    }
    

提交回复
热议问题