TL;DR
如何使用NSSortDescriptor
而不是KeyPath
创建KeyPath
或
如何将PartialKeyPath
转换为KeyPath
当我们在一个SortingOptions
实现中声明EntityPropertyQuery
时,我们将一个KeyPath
传递给EntityQuerySortableByProperty
初始化器。但是我们在entities(matching:)
函数的sortedBy
参数中没有得到相同的sortedBy
。相反,它给了我们一个PartialKeyPath
,并且没有办法(afaik)使用这个PartialKeyPath
对核心数据进行排序,因为NSSortDescriptor
需要一个KeyPath
或String
,而不是PartialKeyPath
。
详细信息
我正在使用来自AppIntents的新查询属性在快捷方式中过滤我的应用程序的数据,但是我无法将它提供给我的排序属性映射到谓词中的排序属性Core。
下面是我的EntityPropertyQuery
实现:
extension ArtistQuery: EntityPropertyQuery {
static var sortingOptions = SortingOptions {
SortableBy(\ArtistEntity.$name)
}
static var properties = QueryProperties {
Property(\ArtistEntity.$name) {
EqualToComparator { NSPredicate(format: "name = %@", $0) }
ContainsComparator { NSPredicate(format: "name CONTAINS %@", $0) }
}
}
func entities(matching comparators: [NSPredicate],
mode: ComparatorMode,
sortedBy: [Sort<ArtistEntity>],
limit: Int?) async throws -> [ArtistEntity] {
Database.shared.findArtists(matching: comparators,
matchAll: mode == .and,
sorts: sortedBy.map { NSSortDescriptor(keyPath: $0.by, ascending: $0.order == .ascending) })
}
}
我的findArtists
方法实现如下:
static func findArtists(matching comparators: [NSPredicate],
matchAll: Bool,
sorts: [NSSortDescriptor]) -> [EArtist] {
...
}
正如我们在entities(matching:)
函数中所看到的,我使用sortedBy
参数中的by
属性来创建NSSortDescriptor
,但是它不能工作,因为NSSortDescriptor
init需要一个KeyPath
,而不是PartialKeyPath
Cannot convert value of type 'PartialKeyPath<ArtistEntity>' to expected argument type 'KeyPath<Root, Value>'
所以,我可以使用NSSortDescriptor
而不是KeyPath
来创建KeyPath
吗?或者可能将PartialKeyPath
转换为KeyPath
发布于 2022-08-30 07:32:39
多亏了这个要旨,我找到了一个解决方案。无法直接将EntityQuerySort转换为NSSortDescriptor。相反,我们必须手动转换它:
private func toSortDescriptor(_ sortedBy: [Sort<ArtistEntity>]) -> [NSSortDescriptor] {
var sortDescriptors = [NSSortDescriptor]()
if let sort = sortedBy.first {
switch sort.by {
case \.$name:
sortDescriptors.append(NSSortDescriptor(keyPath: \EArtist.name, ascending: sort.order == .ascending))
default:
break
}
}
return sortDescriptors
}
https://stackoverflow.com/questions/73542265
复制相似问题