0

我有一个实体项目和一个实体类型(具有属性“名称”),与项目存在一对多关系。(即:项目:棕色桌子,与名称为“咖啡桌”的类型相关)。

我已经以编程方式很好地添加了新项目,例如:

[newItem setValue:([nameTextField stringValue]) forKey:@"Name"];
[newItem setValue:(costNumber) forKey:@"Cost"];
[newItem setValue:(priceNumber) forKey:@"Price"];

我一直在寻找几个小时,但找不到适合我的东西,可以为新项目添加关系。我使用 NSPopUpButton 来选择项目的类型,并尝试了 selectedItem、selectedTag 和 selectedCell 等方法。我正在尝试从我的“typeArray”中获取值,该值填充如下:

NSFetchRequest *fetchRequest2 = [[NSFetchRequest alloc] init];
NSEntityDescription *entity2 = [NSEntityDescription entityForName:@"Type"
                                           inManagedObjectContext:managedObjectContext];
[fetchRequest2 setEntity:entity2];
NSError *error = nil;
typeArray = [managedObjectContext executeFetchRequest:fetchRequest2 error:&error];
if (typeArray == nil) {
    NSLog(@"ERROR");
}
[fetchRequest2 release];

我不确定以下内容是否正确:

NSManagedObject *selectedType = [typeArray objectAtIndex:[typePopUpButton selectedTag]];

但是我没有选择让 selectedType 添加类似“addObject”的选项。

任何帮助表示赞赏,谢谢。

4

1 回答 1

0

This is what I ended up using:

 NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Type"
                                          inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
NSError *error = nil;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Name like %@", [typePopUpButton titleOfSelectedItem]];
[fetchRequest setPredicate:predicate];
NSArray *typeSet = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (typeSet == nil) {
    NSLog(@"ERROR");
}
[fetchRequest release];


NSManagedObject *typeObject = [typeSet objectAtIndex:0];
[typeObject addItemsObject:newItem];

Basically, the object needs to be fetched so that a relationship can be made between the two items, and the predicate is based on the typePopUpButton's titleOfSelectedItem method.

I ensure to only select one object with the method [objectAtIndex:0].

It does bring up a warning though: NSManagedObject may not respond to 'addItemsObject'.

However this does work for me.

于 2012-02-10T22:16:26.527 回答