Basic data. How to get the maximum value from an attribute of an object (Swift)


Recipe

  • recipeID: Int
  • recipeName: String

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

I am new to fast, 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 _ {

    }
}
+4
source share
3 answers

What Apple recommends and is the fastest is the use of NSExpressions. moc is an 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
}
+6
source

Ray Wenderlich Master Data Tutorial Training

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 =).

+2
source
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 results = try context.executeFetchRequest(fetchRequest) as! [Recipe]
        if (results.count > 0) {
            for result in results {
                print(result.recipeID!)
            }
        } else {
            print("No Recipe")
        }
    } catch let error as NSError {
        // failure
        print("Fetch failed: \(error.localizedDescription)")
    }

}

!

+1

Source: https://habr.com/ru/post/1652196/


All Articles