简体   繁体   English

Swift iOS:将数据插入CoreData中的相关实体

[英]Swift iOS : Insert data into related entities in CoreData

I am trying to understand the concept in saving and retrieving records in a one-to-many relationship entities in CoreData. 我试图理解在CoreData中一对多关系实体中保存和检索记录的概念。 i have two tables Products (Master) and Sales (Details) hence (one-to-many) relationship with the relationship key being (sales). 我有两个表,产品(主)和销售(明细),因此(一对多)关系,关系键为(销售)。

Issue 1: when registering a sale to a product. 问题1:注册产品销售时。 i create an instance of the Sales entity, populate the values, then add it to the product.sales (relationship) and attempt a managedObjectContext save. 我创建一个Sales实体的实例,填充值,然后将其添加到product.sales(关系)中,并尝试保存managedObjectContext。

First Question: Do i also have to enter the instance of the Sales entity into the Sales Entity? 第一个问题:我还必须将销售实体的实例输入到销售实体中吗? or that will be updated automatically since there is a relationship? 还是因为存在关系会自动更新?

Second Question: If i want to query all the sales that happened to date, do i query the Sales Entity? 第二个问题:如果我要查询迄今为止发生的所有销售,是否要查询销售实体? or do i query the relationship in the Products Entity? 还是我在产品实体中查询关系?

Thanks for your help! 谢谢你的帮助!

tab images 标签图像

First Question: Do i also have to enter the instance of the Sales entity into the Sales Entity? 第一个问题:我还必须将销售实体的实例输入到销售实体中吗? or that will be updated automatically since there is a relationship? 还是因为存在关系会自动更新?

Something you might not realize here is that you are inherently saving the object by adding it to the managedObjectContext . 您在这里可能没有意识到的一点是,您本质上是通过将对象添加到managedObjectContext来保存对象。 As soon as you do something like 一旦你做类似的事情

let sale = Sale(context: managedObjectContext)

followed by 其次是

managedObjectContext.save()

the context issues a save request to your persistent store (your actual SQL database). 上下文向您的持久性存储(您的实际SQL数据库)发出保存请求。

Therefore your question whether you need to store the Sale as well is answered, it will always be stored upon saving the context. 因此,将回答您是否还需要存储销售的问题,该问题将始终在保存上下文时存储。

Second Question: If i want to query all the sales that happened to date, do i query the Sales Entity? 第二个问题:如果我要查询迄今为止发生的所有销售,是否要查询销售实体? or do i query the relationship in the Products Entity? 还是我在产品实体中查询关系?

That depends... 那要看...

First let me give you a little tip/best practise: 首先,我给您一些小技巧/最佳实践:

Always make sure to set up an inverse relationship 始终确保建立逆向关系

In the Core Data Editor for your Product entity's relationships you can do something like this: Product实体的关系的核心数据编辑器中,您可以执行以下操作:

在此处输入图片说明

Your sales relationships look something like this: 您的销售关系如下所示:

在此处输入图片说明

A relationship is nothing more but a dependency between two entities, therefore there is always an inverse relationship between two entities, make sure you hook them up as shown above. 关系不过是两个实体之间的依赖关系,因此,两个实体之间始终存在逆关系 ,请确保将它们挂钩,如上所示。

Why am I telling you this ? 我为什么要告诉你呢? Remember I mentioned it depends what entity you do your query on ? 还记得我提到过,这取决于您要查询哪个实体? This is where it matters. 这才是重要的。

For example, if you want the Sale for a given Product , you would query the product itself (by querying its relationship called sale ): 例如,如果SaleProductSale ,则可以查询产品本身(通过查询其与sale有关的关系):

let product = [A product instance from your Core Data store]
let sale = product.sale // returns the sale the product is associated to

If you want all the products from a given sale, you would query the Sale entity leveraging the products relationship: 如果要获取给定销售中的所有产品,则可以利用products关系来查询Sale实体:

let sale = [A sale from your Core Data store]
let products = sale.products // the products contained in the sale

You mentioned that you want all the sales to a given date : 您提到要在给定日期进行所有销售

It would not make any sense querying the Product entity for that because each product only has a relationship to the sale it is contained in. 查询Product实体毫无意义,因为每个产品仅与其所含的销售有关系。

So, to answer your question, you should query the Sale entity to retrieve all the sales to a given date. 因此,要回答您的问题,您应该查询Sale实体以检索给定日期的所有销售。

I hope that helps, let me know if something is unclear. 希望对您有所帮助,让我知道是否有不清楚的地方。

    let manageObjectContext = appDelegateObj.managedObjectContext
    let entity =  NSEntityDescription.entityForName("", inManagedObjectContext:manageObjectContext)
let manageObj =  NSManagedObject(entity: entity!,insertIntoManagedObjectContext: manageObjectContext)
manageObj.setValue("Mark Developer", forKey: "AttributeName")
        do {
            try manageObjectContext.save()
        } catch let error as NSError {
            print("Could not save \(error), \(error.userInfo)")
        }

I will need to look into this a bit further, as I too am still getting my head around Core Data, but until I can find the time to do that I think what might work for you is this: 我还需要进一步研究这一点,因为我仍然会继续关注Core Data,但是在找到时间之前,我认为可能对您有用的是:

issue 1: to also enter the sale into the sales entity. 问题1:将销售也输入销售实体。 I do not believe this will be done for you. 我不相信这会为您完成。 Where relationships really become important is in deleting. 关系真正变得重要的地方是删除。 You can specify what you want he delete rules to be, whether nullify, deny, cascade, or no action. 您可以指定要删除规则的内容,无论是取消,拒绝,级联还是不执行任何操作。 Raywenderlich.com has an excellent tutorial series on Core Data that may help you. Raywenderlich.com有一个关于核心数据的优秀教程系列,可能对您有帮助。

issue 2: I think it depends on in which table (although in CoreData the term is ManagedObject) the data you are looking for is stored. 问题2:我认为这取决于要查找的数据存储在哪个表中(尽管在CoreData中,该术语是ManagedObject)。 It would make most sense to me to query the sales entity. 查询销售实体对我而言最有意义。 You don't have to query the whole sales entity if you do not want to. 如果不想,您不必查询整个销售实体。 You can specify search parameters. 您可以指定搜索参数。

As of swift 3 you don't have to create the properties of a class of an entity that you created in Core Data because Core Data does that for you. 从swift 3开始,您不必创建在Core Data中创建的实体的类的属性,因为Core Data会为您执行此操作。 You do have to initialize those properties though. 您确实必须初始化这些属性。 Same thing is true for relationships. 关系也是如此。 For example in the case of the product Class (the parent) the relationship to sales(the child) is already instantiated for you. 例如,对于产品类(父类),已经为您实例化了与销售(子类)的关系。 So you can access and set the Entity Sale by getting the instance of the relationship in the Product Class. 因此,您可以通过获取产品类中的关系实例来访问和设置实体销售。 There might be other ways of doing that but I think using extensions is pretty cool. 可能还有其他方法可以做到,但是我认为使用扩展很酷。

extension Product { 扩展产品{

//You would call this constructor like that: Product(sale) from any //part of your program as long as you "import CoreData" //If its 1 Sale then s 1-1 if it's more than 1 it's 1-many convenience init?(Sale or Sales) { ///您将这样调用此构造函数:只要您“导入CoreData”,就可以从程序的任何//部分调用Product(sale)//如果其1 Sale则为s 1-1,如果大于1则为1-many便利初始化?(销售还是销售){

    let MOC = (UIApplication.shared.delegate as! AppDelegate).managedObjectContext

    self.init(context: MOC)

    //case 1 when sale is 1-many
    let sale = Sale(context: MOC)

    //case 2 when sale is many-many(this can be an array of objects that you sent)

    let sale1 = Sale(context: MOC)
    let sale2 = Sale(context: MOC)
    let sale3 = Sale(context: MOC)

    //setting sale  object
     sale.property = ""

//Now is time to set the relationship with the object that you just set //现在是时候设置与您刚刚设置的对象的关系了

    //case when is 1 - many
    self.sale = sale

    //case when is many - many
    self.sale?.adding(sale1)
    self.sale?.adding(sale2)
    self.sale?.adding(sale3)

} }

Now your Product will be related to your sales.... 现在,您的产品将与您的销售....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM