我已经在互联网上搜索了好几天,寻找关于如何与两个实体一起工作、为数据添加值并链接它们的教程。下面是我的应用程序的设置方式:
我正在制作一个应用程序,允许用户创建一个运动员,在该运动员中,他们可以添加多个体育赛事。我有两个实体:Athletes和Events,从Athletes到Events有一对一的关系,反之亦然。
我面临的问题是要编写哪些代码来在name实体中添加Events和opponent属性值,同时确保该特定名称和对手只匹配最多一名运动员。我尝试过使用核心数据访问器方法,以及为实体创建新的NSManagedObjects,并为特定的键添加值。
我尝试遵循CoreDataRecipes示例代码,以及web上常见的核心数据教程。有人能用一些基本的方法函数或其他帮助你的教程帮助我走上正确的道路吗?谢谢。
发布于 2014-07-10 01:16:16
您需要停止考虑RDBMS (关系数据库),并开始考虑托管对象模型。CoreData负责管理对象及其关联。您可以将运动员对象与事件对象联系起来(顺便说一句,我建议对实体名称使用单数和复数,即运动员和事件对运动员和事件,对一对一的关系使用单数,对多个关系使用复数)。这是一种偏好,但我把自己称为运动员(物体),而不是运动员(物体)。使它更加可读性和直觉以及。
假设您的实体看起来像这样,考虑到您如何描述这些关系:
@interface Athlete : NSManagedObject
@property (nonatomic, retain) NSString * name;
//... a bunch more attributes
@property (nonatomic, retain) Event *event; // use singluar for relationship name too
//...
@end
@interface Event : NSManagedObject
@property (nonatomic, retain) NSString * eventName;
//... a bunch more attributes
@property (nonatomic, retain) NSSet *athletes; // use plural for relationship name
//...
@end
@implementation MyViewController
//... some method
// fetch the athletes (possibly present in table view or other mechanism for selection)
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Athlete"];
NSArray *athletes = [managedObjectContext executeFetchRequest:fetchRequest error:nil];
// select the althletes (primary & opponent - hardcoded for example)
//...
NSArray *selectedAthletes = [NSArray arrayWithObjects: athletes[0], athletes[1], nil];
// create an event
Event *event = [NSEntityDescription
insertNewObjectForEntityForName:@"Event"
inManagedObjectContext:context];
// add the athletes
[event addAthletes:[NSSet setWithArray:selectedAthletes]];
//...
@end现在你和2名运动员有了一场比赛。如果您想要区分对手和挑战者,那么您可以创建2对1的关系(从一个事件到另一个运动员),例如对手和挑战者,并通过如下方式将事件与运动员联系起来:
@interface Event : NSManagedObject
@property (nonatomic, retain) NSString * eventName;
//... a bunch more attributes
@property (nonatomic, retain) Athlete *opponent; // use singluar for relationship name
@property (nonatomic, retain) Athlete *challenger;
//...
@end
//...
event.opponent = athletes[0];
event.challenger = athletes[1];
//...https://stackoverflow.com/questions/24665190
复制相似问题