我在作为父/子关系中的子实体的实体中插入新对象时遇到问题。这是一个具有本地 SQLite 基础的 CoreData 应用程序。主窗口上有 2 个实体,带有 2 个 TableView。使用 contentSet,子表将只显示与所选父级相关的数据。
通过显示带有来自第三个实体的项目表的工作表来向子级添加数据。用户必须从此表中选择,然后单击添加。关闭工作表时,主窗口上的子表应更新为新行。问题:什么都没有出现。
使用第三方应用程序检查数据库内容,我看到新数据在那里,但它没有出现在表格视图中,因为没有存储与父级关系的信息,所以它不知道它是哪个父级涉及。
我的代码缺少有关此的信息,但我只是不知道应该如何编程。换句话说:在关闭工作表时,确定选择了哪个父级并在将新数据插入子级时指定此关系信息。我将不胜感激任何帮助。
这是我的代码:
// there are 3 entities: Collectors (parent), CollectedItems (child) and Items.
// we call the sheet presenting the Items list to pick from
- (IBAction)showAddItemDialog:(id)sender {
[NSApp beginSheet:addItemDialog
modalForWindow:window
modalDelegate:self
didEndSelector:@selector(didEndAddItemSheet:returnCode:contextInfo:)
contextInfo:nil];
}
// we dismiss the sheet by clicking on Cancel or Add
- (IBAction)dismissAddItemDialog:(id)sender {
[NSApp endSheet:addItemDialog returnCode:([sender tag])];
[addItemDialog orderOut:sender];
}
// depending on clicked button, do nothing or pass selected data
- (void)didEndAddItemSheet:(NSWindow *)sheet returnCode:(int)returnCode contextInfo (void *)contextInfo {
if (returnCode == 0) {
// do nothing, this is the effect of clicking on Cancel
}
if (returnCode == 1) {
NSString *theName = [[[itemsPickerController selectedObjects] valueForKey:@"itemName"] objectAtIndex:0];
// above, we get the value from the itemName attribute sleected in the Items list
NSLog (@"%@", theName);
// the variable is displayed in the console, so it was correctly selected
[self addNewItemWithName:theName];
}
}
// we use the passed data to create new object (row) in the CollectedItems entity
- (id)addNewItemWithName:(NSString *)theName {
NSEntityDescription *newContent = [NSEntityDescription insertNewObjectForEntityForName:@"CollectedItems" inManagedObjectContext:[self managedObjectContext]];
[newContent setValue:theName forKey:@"collectedItemName"];
// above, we insert a new row in CollectedItems, assigning the value theName to the attribute collectedItemName
return nil;
}