CoreData一对多和反向关系问题

Alp*_*sta 7 iphone core-data

我试图将一组数据导入CoreData persistentStore.这是将在运行时呈现给用户的只读数据.

我有一个名为"Category"的实体,它与一个名为"Item"的实体有一对多的关系,后者又与Category有反向关系.

当我向上下文添加项目时,如何将它们与正确的类别相关联?我可以在SQLite dB中看到它是通过向Item表添加Category字段来完成的,并且可能使用Categories主键进行关系.但PK是幕后的...有没有一种方法来建立连接?

我还在我的Category类中看到CoreData生成的方法用于添加Items,但我假设这些是alos幕后方法,允许CoreData维护关系:

    @interface Category (CoreDataGeneratedAccessors)

- (void)addItemObject:(Item *)value;
- (void)removeItemObject:(Item *)value;
- (void)addItems:(NSSet *)value;
- (void)removeItems:(NSSet *)value;

@end
Run Code Online (Sandbox Code Playgroud)

我在编程指南中读到CoreData自动处理关系的另一面,但我无法弄清楚如何添加项目时如何进行类别的初始链接.

谢谢

JK

Mas*_*aro 9

有不同的可能性.如果您已经有一个Category对象(例如通过获取请求获得),并假设变量

Category *category;
Item *item;
Run Code Online (Sandbox Code Playgroud)

然后你只需执行以下操作:

item.category = category;
Run Code Online (Sandbox Code Playgroud)

要么

[category setValue: category forKey:@"category"];
Run Code Online (Sandbox Code Playgroud)

并且您已完成,因为Core Data会自动设置反向关系.

如果您没有Category对象,或者要插入新对象,请执行以下操作:

// Create a new instance of the entity 
Category *category = (Category *) [NSEntityDescription insertNewObjectForEntityForName:@"Category" inManagedObjectContext:managedObjectContext];
// add all of the category properties, then set the relationship
// for instance set the category name
[category setValue:@"myCategoryName" forKey:@"name"];
[category setValue:item forKey:@"item"];
Run Code Online (Sandbox Code Playgroud)

然后,像以前一样为Item对象设置此Category对象.最后,您显示的方法不会在Core Data的幕后使用:这些方法可供您使用,因此您还可以执行以下操作:

[category addItemObject:item];
Run Code Online (Sandbox Code Playgroud)

或反过来:

[item addCategoryObject:category];
Run Code Online (Sandbox Code Playgroud)