我使用以下代码将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
答案 0 :(得分:0)
一个常见的错误是在修改托管对象上下文后忘记save
。受管对象上下文只是一个工作区...如果不保存它,则所做的更改将永远不会将其保存到持久性存储中,以后再进行提取请求时,您将看不到更改。所以...请确保您要保存上下文和所有父上下文。