ios - 无法从 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;
})]
解决方案
要获取字典,您必须将泛型指定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 ?? [:]
}
推荐阅读
- android - Firebase 应用程序邀请电子邮件中的链接不起作用
- eclipse - Eclipse - pyqt 应用程序在 MAC 的单独窗口中打开
- r - R - 用于排序变量的 ggplot
- haskell - 是什么使镜头中的 lengthOf 效率低下?
- php - php数组的数组合并
- c++ - gcc 链接器因 .a 文件和 gtest 而失败
- sass - 如何安装 Dart Sass?
- apache-spark - Spark Partitions:从单节点集群上的本地文件系统加载文件
- java - Java多线程应用程序未运行方法
- c# - C# XML 复杂节点列表 - 将每个复杂值存储到新对象中