ios - ios core data中如何设计具有聚合关系的两张表?

标签 ios core-data database-design xcode6

这个问题可能与数据库设计更相关,但我想在 iphone 中使用它,特别是在 xcode 6,核心数据模型中。我有 2 个具有以下关系的类。

旅程 1 ----> 1..* 坐标

所以每个旅程可以有1到多个坐标。 正如您在下图中看到的,我在 journey 中有一个名为 id 的字段,在 coordinate 中有一个名为 journeyId 的字段.

enter image description here

我不知道这个设计是否完美。稍后我想获取每个 Journey 及其坐标。现在,旅程坐标 如下所示:

enter image description here

enter image description here

我的问题是,如何定义一个 NSPredicate 来获取每个 journey 及其相关的 coordinate/s?在此先感谢您的帮助。

最佳答案

首先,我在您的 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.

关于ios - ios core data中如何设计具有聚合关系的两张表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26059680/

相关文章:

快速插入行并带有动画效果

cocoa - 从 XML 切换到 SQLite 核心数据存储时存在哪些潜在障碍?

用于存储年份的 MySQL 类型 : Smallint or Varchar or Date?

ios - 获取应用内购买的订阅到期日期 - 从 appStoreReceiptURL 开始

ios - UILabel 仅在定向后才会增长

ios - 如何在 iOS 8 中将用户限制为只有一个默认键盘?

database - 使用阿姆斯特朗公理计算规范覆盖

iphone - 如何检测点击/单击 UIImageView?

ios - 在 CoreData 中建立关系

mysql - 如何在我的 web 应用程序中模拟垃圾概念?