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

前端 未结 7 785
误落风尘
误落风尘 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:55

    In addition to Ryan's answer, in Swift today, NSManagedObject's execute(_:) returns a NSPersistentStoreResult object, which need some extra code to retrieve the value:

    // Cast `NSPersistentStoreResult` to `NSAsynchronousFetchResult<NSDictionary>`
    let fetchResult = moc.execute(request) as! NSAsynchronousFetchResult<NSDictionary>
    
    // Retrieve array of dictionary result
    let dictsResult = fetchResult.finalResult
    
    // Retrieve and cast the real result
    let key = /* `expressionDescription.name` */
    let result = dictsResult.first!.object(forKey: key) as! /* Your type, depending on `expressionDescription.expressionResultType` */
    

    Note: Force unsafe type cast are used above to simplify code, in real case scenario, you should always avoid this.

    0 讨论(0)
提交回复
热议问题