我有以下文件:
ProductViewController.h
ProductViewController.m
ComponentsViewController.h
ComponentsViewController.m
在里面我有我的按钮,我使用核心数据ProductViewController.m
将产品信息保存到我的sqlite数据库中。在里面ComponentsViewController.m
我有我的按钮来保存组件的信息到我的sqlite。我在我的数据模型中创建了一对多(产品到组件)关系。我的问题是当我保存我的组件信息而不是将组件分配给我已经创建的产品时,信息会保存到当我按下保存组件按钮时创建的“空”产品。在我的代码下方:
ProductViewController.m
- (IBAction)saveProductButton:(id)sender {
// Add product info to Data base
Product *newProduct = [NSEntityDescription insertNewObjectForEntityForName:@"Product" inManagedObjectContext:self.managedObjectContext];
newProduct.prdname = self.name.text;
newProduct.prdtdesc = self.prdtdesc.text;
newProduct.prdtid = self.prdtid.text;
NSError *error;
if (![self.managedObjectContext save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
// 4
self.name.text = @"";
self.prdtid.text = @"";
self.prdtdesc.text = @"";
// 5
[self.view endEditing:YES];
}
ComponentsViewController.m
- (IBAction)addComponent:(id)sender {
Product *newProduct = [NSEntityDescription insertNewObjectForEntityForName:@"Product" inManagedObjectContext:self.managedObjectContext];
Components * newComponent = [NSEntityDescription insertNewObjectForEntityForName:@"Components"
inManagedObjectContext:self.managedObjectContext];
newComponent.prdtcompname = self.prdtcompname.text;
newComponent.prdtcompid = self.prdtcompid.text;
newComponent.prdtcompdesc = self.prdtcompdesc.text;
newComponent.prdtcompqt = self.prdtcompQT.text;
newProduct.tocomponents = [NSSet setWithObjects:newComponent, nil];
NSError *error;
if (![self.managedObjectContext save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
// 4
self.prdtcompQT.text = @"";
self.prdtcompname.text = @"";
self.prdtcompid.text = @"";
self.prdtcompdesc.text = @"";
// 5
[self.view endEditing:YES];
}