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

标签 swift core-data nsfetchrequest


食谱

  • 配方ID:整数
  • 食谱名称:字符串

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

我是 swift 的新手,请帮助我。 提前致谢。

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

    }
}

最佳答案

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
}

关于swift - 核心数据 - 如何从实体属性中获取最大值(Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39102900/

相关文章:

iphone - 如何检索核心数据中实体的唯一关系

ios - 在ios app-Swift中以固定距离对齐两个按钮图像

ios - 应用被拒绝,健康应用权限

swift - 任务组 `async` 与 `spawn`

ios - NSPersisten[NSPersistentStoreCoordinator 崩溃

ios - RestKit/核心数据 : Duplicate objects inserted instead of merged when requesting the same URL twice

ios - 查询 NearGeoPoint 返回空对象

ios - 核心数据 NSFetchedResultsController 和排序

ios - 在 Swift 中从核心数据中检索随机字符串

ios - 使用 NSFetchRequest 按日期和单元格按时区字母顺序对部分进行排序