我有两个实体:TempProducts 和 Products
TempProducts 填充在 TableView 中。用户必须在 tableview 中输入数据。当他单击按钮时,我需要从 TempProducts 获取所有记录并将它们添加到 Products。之后我删除所有 TempProducts 以便下次表为空。
- (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
}