[英]Swift - Accessing multiple entities in core data at the same time
I'm saving objects to my core data, and now I need to save data to two different entities at once. 我正在将对象保存到核心数据中,现在我需要一次将数据保存到两个不同的实体中。 Following my own logic, if I normally save my data like this (which works perfectly): 按照我自己的逻辑,如果我通常这样保存数据(效果很好):
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let contxt: NSManagedObjectContext = appDel.managedObjectContext!
let en = NSEntityDescription.entityForName("MainTable", inManagedObjectContext: contxt)
var newMessage = SecondModel(entity: en!, insertIntoManagedObjectContext: contxt)
newMessage.receiver = object["Receiver"] as String
contxt.save(nil)
I should be able to save to another entity by creating another variable with my different entity like this: 我应该能够通过使用不同的实体创建另一个变量来保存到另一个实体,如下所示:
let enet = NSEntityDescription.entityForName("AlreadyRec", inManagedObjectContext: contxt)
var secondMessage = ThirdModel(entity: enet!, insertIntoManagedObjectContext: contxt)
This gives me the error saying the "ThirdModel has no available initializers, and I don't know what this means or how to solve this issue. Please help me solve this problem. 这给我一个错误,说“ ThirdModel没有可用的初始化程序,并且我不知道这意味着什么或如何解决此问题。请帮助我解决此问题。
Any suggestions on how to proceed would be highly appreciated. 任何有关如何进行的建议将不胜感激。
Your context covers all of Core Data. 您的上下文涵盖了所有核心数据。 Just save at the end. 只需保存到最后。
Some advice: get away from your nondescript naming conventions. 一些建议:摆脱非描述性命名约定。 Don't call your entity MainTable
- that does not even make sense in the SQL world! 不要称呼您的实体MainTable
在SQL世界中甚至没有意义! To my horror I noticed that your managed object model subclass is not called MainTable
but SecondModel
. 令我震惊的是,您注意到您的托管对象模型子类不是MainTable
而是SecondModel
。
If your data describes widgets, you should call your entity and its subclass Widget
. 如果数据描述了小部件,则应调用您的实体及其子类Widget
。 If it is something abstract, such as programming habits, you could call it Habit
. 如果它是抽象的东西,例如编程习惯,则可以将其称为Habit
。 Get the point? 明白这点?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.