CoreData max value get

func datMeetingMaxId() -> Int {
        
        //*****context is DB file stored place
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        
        /// get max Variable declaration
        let expressionDatMeetiongId = "Maxid"
        ///make fetchRequest
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>()
        
        ///make EntityDescription
        //forEntityName is DB name
        //open class func entity(ここ- forEntityName entityName: String, in context: NSManagedObjectContext) -> NSEntityDescription?
        //in : context There is in context
        let entityDescription = NSEntityDescription.entity( forEntityName :"DatMeeting" , in : context)
        
        fetchRequest.entity = entityDescription
        
        //********Make instance
        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]
        
        
        //******Error handling do  try catch
        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)
        }

Leave a Reply

Your email address will not be published. Required fields are marked *