首页 > 解决方案 > 无法从 Swift 中的核心数据获取中获取键值作为字典返回

问题描述

我正在将一些关键值保存到 Profile 实体。但是,我正在尝试获取并作为字典返回,以作为主类的键值。

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]

有什么建议么?如何仅使用字典将其返回到主类?

输出是:

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;
})]

标签: iosswiftcore-data

解决方案


要获取字典,您必须将泛型指定NSFetchRequestNSFetchRequest<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 ?? [:]

}

推荐阅读