核心数据 - 如何从实体属性获取最大值(Swift)

时间:2022-08-25 21:53:48

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?

我有一个带有属性recipeID的实体配方。如何在Swift中将max(recipeID)作为Int值?

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

    }
}

4 个解决方案

#1


7  

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

Apple推荐并且速度最快的方式是使用NSExpressions。 moc是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
}

#2


2  

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)")
    }

}

This works also!

这也有效!

#3


2  

Learning from Ray Wenderlich's Core Data Tutorial

向Ray Wenderlich的核心数据教程学习

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

希望这有助于=)。

#4


0  

To check the max of an entity attribute you can simply use:

要检查实体属性的最大值,您只需使用:

func findMaxRecipeID() -> Int {
    let maxRecipeID = recipe?.value(forKeyPath: "recipe.@max.recipeID") as! Int
    return maxRecipeID
}

You can use this to @sum, @max, @min, @count - saves quite a few lines of code.

你可以使用它来@sum,@ max,@ min,@ count - 保存了不少行代码。

#1


7  

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

Apple推荐并且速度最快的方式是使用NSExpressions。 moc是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
}

#2


2  

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)")
    }

}

This works also!

这也有效!

#3


2  

Learning from Ray Wenderlich's Core Data Tutorial

向Ray Wenderlich的核心数据教程学习

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

希望这有助于=)。

#4


0  

To check the max of an entity attribute you can simply use:

要检查实体属性的最大值,您只需使用:

func findMaxRecipeID() -> Int {
    let maxRecipeID = recipe?.value(forKeyPath: "recipe.@max.recipeID") as! Int
    return maxRecipeID
}

You can use this to @sum, @max, @min, @count - saves quite a few lines of code.

你可以使用它来@sum,@ max,@ min,@ count - 保存了不少行代码。