Michael Michael - 3 months ago 29
Swift Question

Core Data - How can I get the max value from an entity attribute (Swift)




Recipe




  • recipeID: Int

  • recipeName: String



I have an entity Recipe with an attribute recipeID.
How can I get the max(recipeID) as an Int value in Swift?

I'm new in swift, please help me.
Thanks in advance.

func fetchMaxID() {
let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Recipe")

fetchRequest.fetchLimit = 1
let sortDescriptor = NSSortDescriptor(key: "recipeID", ascending: false)
fetchRequest.sortDescriptors = [sortDescriptor]
do {
let maxID = try [managedObjectContext?.executeFetchRequest(fetchRequest)].first
print(maxID)
} catch _ {

}
}

Answer

Learning from Ray Wenderlich's Core Data Tutorial

https://www.raywenderlich.com/115695/getting-started-with-core-data-tutorial/

func fetchMaxRecipe() {
    let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
    let fetchRequest = NSFetchRequest(entityName: "Recipe")

    fetchRequest.fetchLimit = 1
    let sortDescriptor = NSSortDescriptor(key: "recipeID", ascending: false)
    fetchRequest.sortDescriptors = [sortDescriptor]
    do {
        let results = try context.executeFetchRequest(fetchRequest)
        var recipes = [NSManagedObject]()
        recipes = results as! [NSManagedObject]
        let max = recipes.first
        print(max?.valueForKey("recipeID") as! Int)
    } catch _ {

    }
}

Hope this helps =).

Comments