2016-05-24 Swift example of CoreData max query

Here's a copy/paste example of doing the equivalent of a SQL MAX() function. I know, I know "CoreData is an object graph". It's in a project where I had to keep track of the sequence in which entities were added. As far as I know, there's no equivalent of AutoIncrement in CoreData.

    func nextSequence(moc: NSManagedObjectContext) -> Int {
        let quantityExpression = NSExpressionDescription()
        quantityExpression.name = "max.sequence"
        quantityExpression.expression = NSExpression(format: "@max.sequence")
        quantityExpression.expressionResultType = .Integer32AttributeType
        
        let predicate = NSPredicate(format: "form == %@", self.form)
        
        let request = NSFetchRequest()
        request.entity = NSEntityDescription.entityForName("UMAQuestion", inManagedObjectContext: moc)
    //  request.propertiesToGroupBy = ["sequence"]
        request.resultType = NSFetchRequestResultType.DictionaryResultType
        request.propertiesToFetch = [quantityExpression]
        request.predicate = predicate
        
        var maxSequence = 0
        
        do {
            let results = try moc.executeFetchRequest(request) as? [[String:AnyObject]]
            if let maxSequenceDict = results!.first {
                if let maxSequenceResult: AnyObject = maxSequenceDict["max.sequence"] {
                    maxSequence = maxSequenceResult as! Int
                } else {
                    fatalError("Couldn't find max.sequence in dict")
                }
            } else {
                fatalError("Didn't get first result")
            }
        } catch let error as NSError {
            fatalError("Error fetching max sequence: \(error)")
        }
        return maxSequence + 1
    }

Paste this in your model file. Adjust the predicate or uncomment and adjust the propertiesToGroupBy.