加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 02:27:10 所属栏目:百科 来源:网络整理
导读:食谱 recipeID:Int recipeName:String 我有一个带有属性recipeID的实体配方. 如何在Swift中将max(recipeID)作为Int值? 我很快,请帮助我. 提前致谢. func fetchMaxID() { let context = (UIApplication.sharedApplication().delegate as! AppDelegate).man
食谱

> recipeID:Int
> recipeName:String

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

我很快,请帮助我.
提前致谢.

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
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读