核心数据获取:获取 objects 具有一个属性的最大值并且具有另一个共同属性

CoreData Fetch: Getting the objects with the maximum of one atttribute and having another attribute in common

我有一个 CoreData ManagedObject 类型事件,其属性为 name:Sting 和 date:Date。

我想获取名称中包含过滤器的所有 EventObject。如果有多个同名的 object 匹配过滤器,则只返回具有最新日期的 object。

只是为了澄清我想要什么。在基于 table 的方法中,我会在 SQL 中查询,例如:

SELECT name, max(date) FROM Event
WHERE name contains 'filter'
GROUP BY name  

在 CoreData 中我这样尝试,但得到:
无法将类型 'NSKnownKeysDictionary1' 的值转换为 'xx12.Event'

let fetchRequest : NSFetchRequest<Event> = Event.fetchRequest(    fetchRequest.predicate = NSPredicate (format: "name contains %@", filter)
fetchRequest.sortDescriptors = [NSSortDescriptor (key: "name", ascending: true)]
   
// We want Event not Dictionary back 
// fetchRequest.resultType = NSFetchRequestResultType.dictionaryResultType
      
let keypathExpression = NSExpression(forKeyPath: "date")
let maxExpression = NSExpression(forFunction: "max:", arguments: [keypathExpression])

let key = "maxDate"   
let expressionDescription = NSExpressionDescription()
expressionDescription.name = key
expressionDescription.expression = maxExpression
expressionDescription.expressionResultType = .dateAttributeType

fetchRequest.propertiesToFetch = [expressionDescription]
      
let resultEvents = try moc.fetch(fetchRequest)

示例:
如果我有这些 objects

meeting1, 1.1.2020
meeting1, 1.4.2020
meeting2, 1.1.2020
meeting2, 1.4.2020
party, 2.3.2020

和过滤器:会议
我想得到 objects:

meeting1, 1.4.2020
meeting2, 1.4.2020

我会使用基本的获取请求,然后在 swift 代码中执行分组部分,而不是使用 NSExpression

let fetchRequest : NSFetchRequest<Event> = Event.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "name contains %@", filter)

let result = try moc.fetch(fetchRequest)

return Dictionary(grouping: result, by: \.name).values
    .compactMap { [=10=].max {[=10=].date < .date } }