簡體   English   中英

Swift 3 - NSFetchRequest 不同的結果

[英]Swift 3 - NSFetchRequest Distinct Results

任何幫助表示贊賞。

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) 並循環遍歷它們作為創可貼修復,但這並不是解決此問題的正確方法,尤其是在它之前工作的情況下!

訣竅就是讓通用更一般的-而不是<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

通常,我們將它與NSManagedObject一起使用,例如您的BodyType 但是,在這種情況下,由於以下語句,您將獲得字典類型:

fetchRequest.resultType = NSFetchRequestResultType.dictionaryResultType

我在這個答案中概述了 Swift 5.x 的一個簡單的分步方法: https : //stackoverflow.com/a/60101960/171933

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM