Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 _ {

    }
}
like image 534
Michael Avatar asked Aug 23 '16 13:08

Michael


Video Answer


2 Answers

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 recipes = try context.executeFetchRequest(fetchRequest) as! [Recipe]
        let max = recipes.first
        print(max?.valueForKey("recipeID") as! Int)
    } catch _ {

    }
}

Hope this helps =).

like image 144
Mochi Avatar answered Oct 14 '22 06:10

Mochi


The way that Apple recommends and is the fastest is using NSExpressions. moc is a NSManagedObjectContext.

private func getLastContactSyncTimestamp() -> Int64? {

    let request: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest()
    request.entity = NSEntityDescription.entity(forEntityName: "Contact", in: self.moc)
    request.resultType = NSFetchRequestResultType.dictionaryResultType

    let keypathExpression = NSExpression(forKeyPath: "timestamp")
    let maxExpression = NSExpression(forFunction: "max:", arguments: [keypathExpression])

    let key = "maxTimestamp"

    let expressionDescription = NSExpressionDescription()
    expressionDescription.name = key
    expressionDescription.expression = maxExpression
    expressionDescription.expressionResultType = .integer64AttributeType

    request.propertiesToFetch = [expressionDescription]

    var maxTimestamp: Int64? = nil

    do {

        if let result = try self.moc.fetch(request) as? [[String: Int64]], let dict = result.first {
           maxTimestamp = dict[key]
        }

    } catch {
        assertionFailure("Failed to fetch max timestamp with error = \(error)")
        return nil
    }

    return maxTimestamp
}
like image 42
jarora Avatar answered Oct 14 '22 05:10

jarora