gpt4 book ai didi

objective-c - 以父/子关系将数据从工作表传递到 insertNewObject

转载 作者:行者123 更新时间:2023-12-03 17:59:23 24 4
gpt4 key购买 nike

我在作为父/子关系中的子实体的实体中插入NewObject 时遇到问题。它是一个具有本地 SQLite 基础的 CoreData 应用程序。主窗口上有 2 个实体和 2 个 TableView。使用 contentSet,子表将仅显示与所选父级相关的数据。

向子级添加数据是通过显示一张包含来自第三个实体的项目表的工作表来完成的。用户必须从此表中进行选择,然后单击“添加”。关闭工作表时,主窗口上的子表应使用新行进行更新。问题:什么也没有出现。

使用第三方应用程序检查数据库内容,我看到新数据在那里,但它没有出现在 TableView 上,因为没有存储与父级关系的信息,所以它不知道它涉及哪一个父级。

我的代码缺少有关此的信息,但我只是不知道应该如何对其进行编程。换句话说:在取消工作表上,确定选择了哪个父级,并在子级中插入新数据时指定此关系信息。我将不胜感激任何帮助。

这是我的代码:

  // 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;
}

最佳答案

您需要添加您创建的 CollectedItems 对象与其父 Collectors 对象之间的关系。 Collectors 将有一个核心数据实用方法(如果您已生成核心数据管理对象类)。它将被称为类似 addCollectedItemsObject 的名称。

重新加载 tableViews 然后应该使用正确的数据进行更新 - 因为它现在知道关系。

更好的是使用 NSFetchedResultsController 来控制表中的数据,这样当您更新数据模型时,表将自动反射(reflect)更改。

关于objective-c - 以父/子关系将数据从工作表传递到 insertNewObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8989032/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com