Swift3 CoreData 最大値取得 (途中!読まないこと!)
まずimport
import Foundation import UIKit import CoreData
static func maxId() -> Int { //contextはDBファイルそのもの 入れ物を用意 let appDelegate = UIApplication.shared.delegate as? AppDelegate let context = appDelegate?.persistentContainer.viewContext /// ここからが最大値の取得方法 let expressionUserId = "Maxid" /// fetchRequestの生成 let fetchRequest = NSFetchRequest<NSFetchRequestResult>()
\<NSFetchRequestResult はジェネリクス
型をパラメータとして受け取ることができる。ここでは割愛
このクラス定義は
open class NSFetchRequest<ResultType> : NSPersistentStoreRequest, NSCoding where ResultType : NSFetchRequestResult open var entity: NSEntityDescription?
というプロパティを持つ
/// EntityDescriptionの生成 //in : context contextの中にあるという 意味 let entityDescription = NSEntityDescription.entity( forEntityName :"Person" , in : context!)
entityの初期化はこのように記載
それに倣っただけ。
open class func entity(forEntityName entityName: String, in context: NSManagedObjectContext) -> NSEntityDescription?
fetchRequest.entity = entityDescription // let keyPathExpression = NSExpression(forKeyPath: "id") //id を探しますよ、カラムはidを持っていてね let expression = NSExpression(forFunction: "max:", arguments: [keyPathExpression]) let expressionDescription = NSExpressionDescription() expressionDescription.name = expressionUserId expressionDescription.expression = expression expressionDescription.expressionResultType = NSAttributeType.integer64AttributeType fetchRequest.resultType = NSFetchRequestResultType.dictionaryResultType fetchRequest.propertiesToFetch = [expressionDescription]
propertiesToFetchは配列を渡さないといけない
**定義はこうなっている
open var propertiesToFetch: [Any]?
//エラーハンドリング do{ let results = try context?.fetch(fetchRequest) if let maxId = ((results?.first as AnyObject).value(forKey: expressionUserId)) as? Int { print("maxId = \(maxId)") return maxId + 1 } else{ return 1 } } catch let error { print(error) } return -1 }