问题
I have two entities: TempProducts and Products
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
}
回答1:
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.
来源:https://stackoverflow.com/questions/19188323/core-data-how-to-get-records-from-an-entity-and-add-them-to-another-entity