如何从核心数据的单个字段中获得不同的结果(Swift 4) [英] How to get distinct results from a single field in Core Data (Swift 4)

查看:77
本文介绍了如何从核心数据的单个字段中获得不同的结果(Swift 4)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 LogLine表的 flightNumber字段中获取所有值的明确列表。但是我尝试过的所有操作都导致获取请求返回了航班号的完整列表,并且重复了。

I'm trying to get a distinct list of all of the values from the "flightNumber" field in my "LogLine" table. But everything I've tried has resulted in the fetch request returning the full list of flight numbers, with duplicates.

我已经遵循了以下问题的答案:

I've followed the answers from these questions:

Swift核心数据-请求效果明显

Swift 3-NSFetchRequest不同的结果

但似乎无法使其正常工作。这是我的代码:

But can't seem to get it to work. Here is my code:

func fetchUniqueFlightNumbers() -> [[String: Int16]]? {
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "LogLine")
    request.resultType = NSFetchRequestResultType.dictionaryResultType
    request.returnsDistinctResults = true
    request.propertiesToFetch = ["flightNumber"]

    do {
        let results = try persistenceContainer.viewContext.fetch(request) as! [[String: Int16]]
        return results
    } catch {
        print("Couldn't read flight numbers from DB \(error)")
        return nil
    }
}

我得到的结果是:

[["flightNumber": 1], ["flightNumber": 1], ["flightNumber": 2], ["flightNumber": 2]]

我想得到结果[1,2],但我得到了[1, 1,2,2]。

I want to get the result [1,2] but I'm getting [1,1,2,2].

属性 flightNumber是一个整数16。

The attribute "flightNumber" is an Integer 16.

我的代码有问题吗?在Swift 4中有什么变化吗?

Is there something wrong with my code, or has something changed in Swift 4?

编辑:

我意识到我只是在测试中看到了这种行为,当我的持久性存储配置为NSInMemoryStoreType时。因此,这并不是什么大问题,我只需要重新考虑这部分代码的单元测试。我很好奇为什么我会看到两种商店类型之间的行为差​​异。

I realized that I'm only seeing this behavior in testing, when my persistent store is configured as an NSInMemoryStoreType. So it isn't as much of a problem, I'll just have to rethink the unit tests for this part of the code. I am curious why I'm seeing this difference in behavior between the two store types though.

推荐答案

@ Chris.BI看到您的帖子有点旧,但尚未解决。我只是遇到了类似的问题,但是使用 FethchedResultController ,我发现了很多东西。您遇到的问题是您没有使用 .propertiesToGroupBy ,而这正是您希望获得不同结果的属性。它是必需的 NSFetchRequest 属性,必须使用它才能获得不同的结果。要获得完整的见解,请查看我对自己问题的回答,这是一种非常详细的分步指南。 从中删除重复的对象根据对象参数UPDATED Swift获取数据
希望有帮助。

@Chris.B I see your post is a bit old but unsolved. I just went through a similar problem but using FethchedResultControllerand I found out a lot. The problem you're having is that you're not using .propertiesToGroupBy and this is the properties you want distinct results of. It is a mandatory NSFetchRequest property and must be used in order to get distinct results. For a complete insight check my answer at my own question as is a very detailed sort of step-by-step guide. Removing duplicate objects from fetch based on object parameter UPDATED Swift Hope it helps.

这篇关于如何从核心数据的单个字段中获得不同的结果(Swift 4)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆