Swift核心数据多对多关系不保存实体
Posted
技术标签:
【中文标题】Swift核心数据多对多关系不保存实体【英文标题】:Swift core data many-to-many relationship not saving entities 【发布时间】:2019-06-13 19:16:31 【问题描述】:我使用以下代码将pokemon
实体添加到user
中的pokemons
关系,其中pk
是NSManagedObject
类型pokemon
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else return
let managedContext = appDelegate.persistentContainer.viewContext let fetchRequest = NSFetchRequest <NSManagedObject>
(entityName: "User")
let pokemonRequest = NSFetchRequest <NSManagedObject>
(entityName: "Pokemon")
let manyRelation = user.value(forKeyPath: "pokemons") as! NSMutableSet
manyRelation.add(pk)
do
try managedContext.save()
catch let error as NSError
print ("Could not save. \(error), \(error.userInfo)")
应用程序显示user
在pokemons
关系中有一个口袋妖怪实体。我移动到个人资料视图以使用以下代码查看您的口袋妖怪:
let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let destination = storyboard.instantiateViewController(withIdentifier: "ProfileViewController") as! ProfileViewController
self.navigationController?.pushViewController(destination, animated: true)
我使用此代码加载用户数据的位置:
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else return
let managedContext = appDelegate.persistentContainer.viewContext let fetchRequest = NSFetchRequest <NSManagedObject>
(entityName: "User")
do
let users = try managedContext.fetch (fetchRequest)
for user in users
let name = user.value (forKey: "username")
as? String let pks = user.value (forKey: "pokemons")
as? NSMutableSet if name = = username
for pokemon in pks!
self.pokemonsList.append (pokemon as! NSManagedObject)
catch let error as NSError
print ("Could not fetch. \(error), \(error.userInfo)")
但是,pks
变量始终为空。为什么变量总是空的? user
变量确实有 pokemons
填充:
pokemons = "<relationship fault: 0x600001726da0 'pokemons'>";
【问题讨论】:
【参考方案1】:一个常见的错误是在修改托管对象上下文后忘记save
。托管对象上下文只是一个工作区......如果您不保存它,您的更改永远不会进入持久存储,并且您稍后发出获取请求时将看不到您的更改。所以...确保您正在保存上下文和任何父上下文。
【讨论】:
添加到我做的 manyRelation 之后:尝试 managedContext.save() 您应该显示该代码以及检查错误的代码。以上是关于Swift核心数据多对多关系不保存实体的主要内容,如果未能解决你的问题,请参考以下文章