簡體   English   中英

無法從 Swift 中的核心數據提取中獲取鍵值作為字典返回

[英]Not able to take key values to return as dictionary from Core data fetch in Swift

我正在將一些關鍵值保存到 Profile 實體。 但是,我正在嘗試獲取並作為字典返回,以作為主要 class 的鍵值。

static func fetchProfile) -> [String: Any]? {
    let delegate = UIApplication.shared.delegate as! AppDelegate
    let context = delegate.persistentContainer.viewContext
    let profileFetch = NSFetchRequest<NSFetchRequestResult>(entityName: AccountinfoKeyConstant.Entity_Profile)
    var fetchedObjects: [String: Any]?

    var entityDescription: NSEntityDescription? = nil
    entityDescription = NSEntityDescription.entity(forEntityName: AccountinfoKeyConstant.Entity_Profile, in: context)
    profileFetch.entity = entityDescription
    do {
        let objects = try context.fetch(profileFetch)
        print("objects \(objects)")
        fetchedObjects = objects as [String: Any]
    } catch let error as NSError {
        print("Could not fetched. \(error), \(error.userInfo)")
    }
    return fetchedObjects

}

在上面的代碼中,我收到以下錯誤:

無法將類型“[Any]”的值強制轉換為類型“[String: Any]”

對於這一行fetchedObjects = objects as [String: Any]

有什么建議么? 如何僅將字典返回到主 class?

Output 是:

objects [<Profile: 0x6000026c3ca0> (entity: Profile; id: 0x8d815a305b375e8d <x-coredata://F92995FE-578E-48EB-AA07-242ECBBBBFE4/Profile/p20>; data: {
     birthdate = "04/22/2020";
     email = "example@test.com";
    "family_name" = myName;
    gender = " ";
    "given_name" = myName123;
    name = name123;
})]

要獲取字典,您必須將通用NSFetchRequest指定為NSFetchRequest<NSDictionary>並添加dictionaryResultType

然而,獲取對象總是返回一個非可選數組。

進一步使方法throw大大減少了代碼。

static func fetchProfile() -> [[String: Any]] throws {
    let delegate = UIApplication.shared.delegate as! AppDelegate
    let context = delegate.persistentContainer.viewContext
    let profileFetch : NSFetchRequest<NSDictionary> = NSFetchRequest(entityName: AccountinfoKeyConstant.Entity_Profile)
    profileFetch.resultType = .dictionaryResultType

    return try context.fetch(profileFetch) as! [[String:Any]]

}

如果實體中只有一條記錄,則返回第一項

static func fetchProfile() -> [String: Any] throws {
    let delegate = UIApplication.shared.delegate as! AppDelegate
    let context = delegate.persistentContainer.viewContext
    let profileFetch : NSFetchRequest<NSDictionary> = NSFetchRequest(entityName: AccountinfoKeyConstant.Entity_Profile)
    profileFetch.resultType = .dictionaryResultType
    let result = try context.fetch(profileFetch) as! [[String:Any]]
    return result.first ?? [:]

}

暫無
暫無

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

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