Swift核心数据多对多关系而不保存实体

时间:2019-06-13 19:16:31

标签: ios swift xcode core-data

我使用以下代码将pokemon实体添加到pokemons中的user关系中,其中pk是类型{{1}的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

1 个答案:

答案 0 :(得分:0)

一个常见的错误是在修改托管对象上下文后忘记save。受管对象上下文只是一个工作区...如果不保存它,则所做的更改将永远不会将其保存到持久性存储中,以后再进行提取请求时,您将看不到更改。所以...请确保您要保存上下文和所有父上下文。