食谱
> 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 }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。