这个问题可能与数据库设计更相关,但我想在 iphone 中使用它,特别是在 xcode 6,核心数据模型中。我有 2 个具有以下关系的类。
旅程
1 ----> 1..* 坐标
所以每个旅程
可以有1到多个坐标
。
正如您在下图中看到的,我在 journey
中有一个名为 id
的字段,在 coordinate
中有一个名为 journeyId
的字段.
我不知道这个设计是否完美。稍后我想获取每个 Journey 及其坐标。现在,旅程
和坐标
如下所示:
我的问题是,如何定义一个 NSPredicate
来获取每个 journey
及其相关的 coordinate
/s?在此先感谢您的帮助。
最佳答案
首先,我在您的 CoreData 模型中观察到,您已经指出您将只有 1 个坐标——您应该会看到一个双箭头。在CoreData Editor中选择箭头,在右侧工具栏勾选Data Model Inspector
@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.
关于ios - ios core data中如何设计具有聚合关系的两张表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26059680/