核心数据 - 如何从一个实体获取记录,并将其添加到另一个实体 [英] Core data - how to get records from an entity and add them to another entity

查看:266
本文介绍了核心数据 - 如何从一个实体获取记录,并将其添加到另一个实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个实体:TempProducts和产品

I have two entities: TempProducts and Products

TempProducts在TableView中填充。
当他点击一个按钮,我需要从TempProducts得到的所有记录,并添加他们Products.After我删除所有TempProducts为了表是空的下一次用户必须在tableview.Than输入数据。

TempProducts is populated in TableView. The user must enter the data in the tableview.Than when he clicks on a button i need to get all records from TempProducts and add them to Products.After that i delete all TempProducts in order the table to be empty for next time.

- (IBAction)saveData:(id)sender

{

//FETCH ALL RECORDS OF TEMPPRODUCTS
NSFetchRequest * allTempProducts = [[NSFetchRequest alloc] init];
[allTempProducts setEntity:[NSEntityDescription entityForName:@"TempProducts" inManagedObjectContext:self.managedObjectContext]];
[allTempProducts setIncludesPropertyValues:NO]; //only fetch the managedObjectID


//FETCH ALL RECORDS OF TEMPPRODUCTS
NSFetchRequest * allProducts = [[NSFetchRequest alloc] init];
[allProducts setEntity:[NSEntityDescription entityForName:@"Products" inManagedObjectContext:self.managedObjectContext]];
[allProducts setIncludesPropertyValues:NO]; //only fetch the managedObjectID

NSError * error = nil;
NSArray * tProducts = [self.managedObjectContext executeFetchRequest:allTempProducts error:&error];

NSArray * products = [self.managedObjectContext executeFetchRequest:allProducts error:&error];


NSLog(@"The array TempProducts has %li records", [tProducts count]);
NSLog(@"The array Products has %li records", [products count]);

//-------------------------------------------------------------------------

//ADD OBJECT TO PRODUCTS

NSManagedObjectContext *con = [self managedObjectContext];
NSManagedObject *countryObject=[NSEntityDescription
                                insertNewObjectForEntityForName:@"Products"
                                inManagedObjectContext:con];



//--------------------------------------------------------------------------
//error handling goes here
for (NSManagedObject * tProduct in tProducts) {
    [self.managedObjectContext deleteObject:tProduct];
}
NSError *saveError = nil;
[self.managedObjectContext save:&saveError];
//more error handling here

}

推荐答案

您可以通过使用只有一个实体解决这个问题:产品,但有一个额外的布尔属性 isTemp 。这将简化您所描述的用例,但可能会复杂化code的其他部分,例如在每一个取你要记得只获取临时的或不是暂时的对象。

You could solve it by using only one entity: Products, but with one additional boolean attribute isTemp. It would simplify the use case you describe, but might complicate other parts of the code, e.g. in every fetch you'd have to remember to fetch only temporary or not temporary objects.

这篇关于核心数据 - 如何从一个实体获取记录,并将其添加到另一个实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆