【发布时间】:2020-07-20 21:53:32
【问题描述】:
我目前正在开发一个带有多用户系统的项目。用户可以使用 CoreData 创建永久保存的新配置文件。
我的问题是:一次只能激活一个配置文件,所以我想获取创建的配置文件的 ObjectID 并将其保存到用户默认值。
此外,我在想,只要我需要活动配置文件的数据,我就可以简单地从 UserDefaults 获取 ObjectID 并执行 READ - Request,它只会给我返回 结果与那个特定的ObjectID。
到目前为止我保存数据的代码:
// 1. Create new profile entry to the context.
let newProfile = Profiles(context: context)
newProfile.idProfileImage = idProfileImage
newProfile.timeCreated = Date()
newProfile.gender = gender
newProfile.name = name
newProfile.age = age
newProfile.weight = weight
// 2. Save the Object ID to User Defaults for "activeUser".
// ???????????????????
// ???????????????????
// 3. Try to save the new profile by saving the context to the persistent container.
do {
try context.save()
} catch {
print("Error saving context \(error)")
}
到目前为止我用于读取数据的代码
// 1. Creates an request that is just pulling all the data.
let request: NSFetchRequest<Profiles> = Profiles.fetchRequest()
// 2. Try to fetch the request, can throw an error.
do {
let result = try context.fetch(request)
} catch {
print("Error reading data \(error)")
}
如您所见,我无法实现第一个代码块的第 2 部分。新配置文件已保存,但 ObjectID 未保存到 UserDefaults。
另外第二个代码块的第一方不是最终目标。该请求只会返回该实体的所有数据,而不仅仅是我存储在用户默认值中的具有 ObjectID 的数据。
我希望你们对如何解决这个问题有一个想法。 提前感谢您的帮助!
【问题讨论】:
-
为什么不直接向您的实体添加一个属性 isCurrent,而不是混合 UserDefaults 和 CoreData?
标签: ios swift xcode sqlite core-data