如何在ios核心数据中设计两个具有聚合关系的表?

时间:2014-09-26 12:33:32

标签: ios core-data database-design xcode6

这个问题可能与数据库设计有关,但我想在iphone中专门用于xcode 6核心数据模型。我有2个课程,关系如下。

Journey 1 ----> 1 .. * Coordinates

因此每个journey可以有1到多个coordinates。 如下图所示,我在journey中有一个名为id的字段,coordinate中有一个名为journeyId的字段。

enter image description here

我不知道这个设计是否完美。后来我想用它的坐标获取每个旅程。现在journeycoordinates看起来像这样:

enter image description here

enter image description here

我的问题是,如何定义NSPredicate以获取每个journey及其相关的coordinate / s?提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

首先我在你的CoreData模型中观察到,你已经表明你只有1个坐标 - 你应该看到一个双箭头。选择CoreData Editor中的箭头,然后选中右侧工具栏中的Data Model Inspector model change

@interface Journey : NSManagedObject
    @property (nonatomic, retain) NSString *journeyName;
    @property (nonatomic, retain) NSNumber *journeyId;
    @property (nonatomic, retain) NSSet *coordinates;  // NSSet of Coordinates
@end

请注意,集合一对多关系是无序集合 - 您可能需要在坐标对象上包含排序索引。

所以获取数据就像这样:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO];

[fetchRequest setSortDescriptors:@[sortDescriptor]];

[fetchRequest setEntity:[NSEntityDescription entityForName:@"Journey" inManagedObjectContext:_managedObjectContext]];

NSError *error = nil;
NSArray *results = [_managedObjectContext executeFetchRequest:fetchRequest error:&error];

// results now contains a sorted (by name) of Journey -- and each journey has a collection (unsorted) -- which you can sort by an index added at insertion time.