Swift 3 - NSFetchRequest不同的结果

时间:2016-10-22 11:30:09

标签: ios swift distinct nsfetchrequest

任何帮助表示赞赏。

Xcode自动更新为8 ...我正在瞄准IOS 9.3

将所有代码转换过来,但现在有一件事情已经破裂,我在类似的问题中尝试了各种建议!我之前正在工作的 的抓取请求正在中断。

我的目标是获得一份清晰的清单。该应用程序崩溃了:

let results = try context.fetch(fetchRequest) 

控制台中描述的错误为:

Could not cast value of type 'NSKnownKeysDictionary1' (0x10fd29328) to 'MyApp.BodyType' (0x10eebc820).

这是函数

func getBodyTypes() {
            let context = ad.managedObjectContext
            let fetchRequest = NSFetchRequest<BodyType>(entityName: "BodyType")
            fetchRequest.propertiesToFetch = ["name"]
            fetchRequest.returnsDistinctResults = true
            fetchRequest.resultType = NSFetchRequestResultType.dictionaryResultType

            do {
                let results = try context.fetch(fetchRequest)

                for r in results {
                    bodyTypes.append(r.value(forKey: "name") as! String)
                }
            } catch let err as NSError {
                print(err.debugDescription)
            }
}

如果下面的行被隐藏,它不会破坏,但后来我没有得到我想要的!

fetchRequest.resultType = NSFetchRequestResultType.dictionaryResultType 

我理解我可以使用所有结果(4300)并将它们作为一个bandaid修复程序循环,但这并不是解决这个问题的正确方法,特别是因为它之前正在工作!

2 个答案:

答案 0 :(得分:13)

诀窍是使通用更通用 - 而不是在获取请求中使用<BodyType>,使用<NSFetchRequestResult>

let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "BodyType")

此获取请求的结果为[Any],因此您需要在使用之前强制转换为相应的字典类型。例如:

func getBodyTypes() {
    let context = ad.managedObjectContext
    // 1) use the more general type, NSFetchRequestResult, here:
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "BodyType")
    fetchRequest.propertiesToFetch = ["name"]
    fetchRequest.returnsDistinctResults = true
    fetchRequest.resultType = NSFetchRequestResultType.dictionaryResultType

    do {
        let results = try context.fetch(fetchRequest)

        // 2) cast the results to the expected dictionary type:
        let resultsDict = results as! [[String: String]]

        for r in resultsDict {
            bodyTypes.append(r["name"])
        }

    } catch let err as NSError {
        print(err.debugDescription)
    }
}

注意:NSFetchRequestResult是一种协议,由四种类型采用:
- NSDictionary
- NSManagedObject
- NSManagedObjectID
- NSNumber

通常,我们会将NSManagedObjectBodyType一起使用,例如fetchRequest.resultType = NSFetchRequestResultType.dictionaryResultType 。但是,在这种情况下,由于语句:

,您将获得字典类型
CREATE TABLE Abbreviations (LongTerm VARCHAR(100),ShortTerm VARCHAR(10));
INSERT INTO Abbreviations VALUES
 ('ASSEMBLY','ASSY')
,('FEEd','FD')
,('FLUSH','FL')
,('HOUSING','HSG')
,('LENS','LNS')
,('RECESSED','REC');

GO

答案 1 :(得分:0)

在此答案中,我为Swift 5.x概述了一种简单的分步方法:https://stackoverflow.com/a/60101960/171933