首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >核心数据:使用PartialKeyPath而不是KeyPath进行排序

核心数据:使用PartialKeyPath而不是KeyPath进行排序
EN

Stack Overflow用户
提问于 2022-08-30 12:12:10
回答 1查看 28关注 0票数 1

TL;DR

如何使用NSSortDescriptor而不是KeyPath创建KeyPath

如何将PartialKeyPath转换为KeyPath

当我们在一个SortingOptions实现中声明EntityPropertyQuery时,我们将一个KeyPath传递给EntityQuerySortableByProperty初始化器。但是我们在entities(matching:)函数的sortedBy参数中没有得到相同的sortedBy。相反,它给了我们一个PartialKeyPath,并且没有办法(afaik)使用这个PartialKeyPath对核心数据进行排序,因为NSSortDescriptor需要一个KeyPathString,而不是PartialKeyPath

详细信息

我正在使用来自AppIntents的新查询属性在快捷方式中过滤我的应用程序的数据,但是我无法将它提供给我的排序属性映射到谓词中的排序属性Core。

下面是我的EntityPropertyQuery实现:

代码语言:javascript
运行
复制
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方法实现如下:

代码语言:javascript
运行
复制
static func findArtists(matching comparators: [NSPredicate],
                        matchAll: Bool,
                        sorts: [NSSortDescriptor]) -> [EArtist] {
    ...
}

正如我们在entities(matching:)函数中所看到的,我使用sortedBy参数中的by属性来创建NSSortDescriptor,但是它不能工作,因为NSSortDescriptor init需要一个KeyPath,而不是PartialKeyPath

代码语言:javascript
运行
复制
Cannot convert value of type 'PartialKeyPath<ArtistEntity>' to expected argument type 'KeyPath<Root, Value>'

所以,我可以使用NSSortDescriptor而不是KeyPath来创建KeyPath吗?或者可能将PartialKeyPath转换为KeyPath

EN

回答 1

Stack Overflow用户

发布于 2022-08-30 15:32:39

多亏了这个要旨,我找到了一个解决方案。无法直接将EntityQuerySort转换为NSSortDescriptor。相反,我们必须手动转换它:

代码语言:javascript
运行
复制
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
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73542265

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档