親/子関係の子であるエンティティに InsertNewObject を挿入する際に問題があります。これは、ローカル SQLite ベースの CoreData アプリです。メイン ウィンドウに 2 つの TableView で表示される 2 つのエンティティがあります。contentSet を使用すると、子のテーブルには、選択した親に関連するデータのみが表示されます。
子にデータを追加するには、3 番目のエンティティからの項目のテーブルを含むシートを表示します。ユーザーはこのテーブルから選択し、[追加] をクリックする必要があります。シートを閉じると、メイン ウィンドウの子テーブルが新しい行で更新されます。問題: 何も表示されません。
サードパーティのアプリでデータベースの内容を確認すると、新しいデータがあることがわかりますが、親との関係に関する情報が保存されていないため、テーブル ビューに表示されないため、どの親にデータが送信されたかわかりません。関係します。
私のコードにはこれに関する情報がありませんが、これをどのようにプログラムすればよいかわかりません。つまり、シートを閉じるときに、選択されている親を特定し、子に新しいデータを挿入するときにこの関係情報を指定します。助けていただければ幸いです。
これが私のコードです:
// 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;
}