###前提・実現したいこと
ここに質問したいことを詳細に書いてください
swift3 coredataを利用して、entityの中の最大値を取得したいです。
一応今のコードがあるのですが、汚くて、もう少しきれいにならないかと思います
よろしくお願いします
コード static func datMeetingMaxId() -> Int { //***********teacher-- contextはDBファイルそのもの 入れ物を用意 永続化ストア let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext /// ここからが最大値の取得方法 let expressionDatMeetiongId = "Maxid" /// fetchRequestの生成 let fetchRequest = NSFetchRequest<NSFetchRequestResult>() // EntityDescriptionの生成 //in : context contextの中にあるという意味 上記永続化ストア let entityDescription = NSEntityDescription.entity( forEntityName :"DatMeeting" , in : context) fetchRequest.entity = entityDescription let keyPathExpression = NSExpression(forKeyPath: "id") let expression = NSExpression(forFunction: "max:", arguments: [keyPathExpression]) let expressionDescription = NSExpressionDescription() expressionDescription.name = expressionDatMeetiongId expressionDescription.expression = expression expressionDescription.expressionResultType = NSAttributeType.integer64AttributeType fetchRequest.resultType = NSFetchRequestResultType.dictionaryResultType fetchRequest.propertiesToFetch = [expressionDescription] //******エラーハンドリング do{ let results = try context.fetch(fetchRequest) if let maxId = ((results.first as AnyObject).value(forKey: expressionDatMeetiongId)) as? Int { print("maxId = (maxId)") return maxId + 1 } else{ return 1 } } catch let error { print(error) } return -1 }
エラーメッセージ
エラーはありません ```swift3 ###試したこと ###補足情報(言語/FW/ツール等のバージョンなど) Xcode Version 9.0 Mac os 10.12.6 Sierra
あなたの回答
tips
プレビュー