我有以下文件:核心數據關係
ProductViewController.h
ProductViewController.m
ComponentsViewController.h
ComponentsViewController.m
裏面ProductViewController.m
我有我的按鈕,我通過使用核心數據的產品的信息保存到我的的SQLite數據庫。 Inside 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];
}
你爲什麼要創建一個新的產品,那麼在'addComponents:'如果你想添加到現有的產品? –