Core Data - How to fetch an entity with max value property

前端 未结 7 801
误落风尘
误落风尘 2020-12-05 02:06

I have a entity Person with a property personId (personId is unique)

How can I fetch the Person with the max personId?

(I want to f

7条回答
  •  感动是毒
    2020-12-05 02:45

    The answer given above using NSExpression is correct. Here is the Swift version.

    private func getLastSyncTimestamp() -> Int64? {
    
    let request: NSFetchRequest = NSFetchRequest()
    request.entity = NSEntityDescription.entity(forEntityName: "EntityName", in: self.moc)
    request.resultType = NSFetchRequestResultType.dictionaryResultType
    
    let keypathExpression = NSExpression(forKeyPath: "timestamp")
    let maxExpression = NSExpression(forFunction: "max:", arguments: [keypathExpression])
    
    let key = "maxTimestamp"
    
    let expressionDescription = NSExpressionDescription()
    expressionDescription.name = key
    expressionDescription.expression = maxExpression
    expressionDescription.expressionResultType = .integer64AttributeType
    
    request.propertiesToFetch = [expressionDescription]
    
    var maxTimestamp: Int64? = nil
    
    do {
    
        if let result = try self.moc.fetch(request) as? [[String: Int64]], let dict = result.first {
           maxTimestamp = dict[key]
        }
    
    } catch {
        assertionFailure("Failed to fetch max timestamp with error = \(error)")
        return nil
    }
    
    return maxTimestamp
    }
    

    where moc is a NSManagedObjectContext.

提交回复
热议问题