1
votes

This is my fetch request:

    let request = NSFetchRequest<Service>()
    let sorter = NSSortDescriptor(key: "date", ascending: true)

    let entity = NSEntityDescription()
    entity.name = "Service"
    request.entity = entity
    request.sortDescriptors = [sorter]
    request.resultType = .dictionaryResultType
    request.predicate = NSPredicate(format: "month.identifier = 201703")

    let exp = NSExpressionDescription()
    exp.expression = NSExpression(forKeyPath: "@sum.duration")
    exp.expressionResultType = .integer64AttributeType
    request.propertiesToFetch = [exp]

    do {
        let result = try NSManagedObjectContext.mr_default().fetch(request) //error is here
        print("+++++ \(result)")
    } catch {
        print(error)
    }

But it produces an error:

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[__NSArrayM insertObject:atIndex:]: object cannot be nil'

Why?

1

1 Answers

2
votes

Set the name for NSExpressionDescription. The name is the key that will be used in the dictionary for the return value. I have changed result type for fetch request to make it work for Dictionary type.

    let request = NSFetchRequest<NSFetchRequestResult>()
    let sorter = NSSortDescriptor(key: "date", ascending: true)

    let entity = NSEntityDescription()
    entity.name = "Service"
    request.entity = entity
    request.sortDescriptors = [sorter]
    request.resultType = .dictionaryResultType
    request.predicate = NSPredicate(format: "month.identifier = 201703")

    let exp = NSExpressionDescription()
    exp.name = "sumOfduration"
    exp.expression = NSExpression(forKeyPath: "@sum.duration")
    exp.expressionResultType = . integer64AttributeType
    request.propertiesToFetch = [exp]

    do {
        let result = try UMUserDBManager.sharedInstance.getThreadManagedObjectContext().fetch(request) //error is here
        print("+++++ \(result)")
    } catch {
        print(error)
    }

}