如何以一对多关系访问数据?

时间:2011-02-21 18:18:34

标签: objective-c cocoa-touch core-data one-to-many

我2个月前才买了我的第一本如何编程的书,所以我知道这可能是非常基本的,但我正在努力学习如何使用Core Data,而我无法弄清楚如何从对象中检索数据在一对多的关系中。我花了一整天的谷歌搜索和阅读Apple文档,但找不到一个非常简单的解释。

我已使用以下实体设置核心数据模型:

“旅行”与“核对清单”之间存在一对多的关系......

“核对表”与“checklistItems”之间存在一对多的关系......

“ChecklistItem”。

然后,在我的App Delegate中,在applicationDidFinishLaunching:中,我添加了以下简单代码,它只创建了一些托管对象,然后在控制台中显示它们:

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    

    // Override point for customization after application launch.

    // TEST CORE DATA - MAKE OBJECTS
    NSManagedObjectContext *context = [self managedObjectContext];
    NSManagedObject *trip = [NSEntityDescription insertNewObjectForEntityForName:@"Trip" inManagedObjectContext:context];
    [trip setValue:@"Test Trip" forKey:@"tripName"];

    NSManagedObject *checklist = [NSEntityDescription insertNewObjectForEntityForName:@"Checklist" inManagedObjectContext:context];
    [checklist setValue:@"Test Checklist" forKey:@"checklistName"];


    NSManagedObject *checklistItem = [NSEntityDescription insertNewObjectForEntityForName:@"ChecklistItem" inManagedObjectContext:context];
    [checklistItem setValue:@"Test Checklist Item" forKey:@"checklistItemName"];
    [checklistItem setValue:[NSNumber numberWithBool:TRUE] forKey:@"checklistItemChecked"];
    NSError *error;
    if (![context save:&error]) {
        NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
    }

    // TEST CORE DATA - LIST OBJECTS
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setEntity:[NSEntityDescription entityForName:@"Trip" inManagedObjectContext:context]];

    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
    for (NSManagedObject *info in fetchedObjects) {
        NSLog(@"Trip Name: %@", [info valueForKey:@"tripName"]);

        NSManagedObject *aChecklist = [info valueForKey:@"checklists"];
        NSLog(@"Checklist Name: %@", [aChecklist valueForKey:@"checklistName"]);

        NSManagedObject *aChecklistItem = [aChecklist valueForKey:@"checklistItems"];
        NSLog(@"Checklist Item Name: %@", [aChecklistItem valueForKey:@"checklistItemName"]);
        NSLog(@"Checklist Item Checked: %@", [aChecklistItem valueForKey:@"checklistItemChecked"] ? @"Yes it is!" : @"No It's Not!");
    }
    [fetchRequest release];

    [self.window makeKeyAndVisible];

    return YES;
}

当我运行程序时,我在终端中获得以下内容:

  

2011-02-21 18:01:14.144 BYG [38204:207]旅行名称:Test Trip   2011-02-21 18:01:14.146 BYG [38204:207]清单名称:{(   )}   2011-02-21 18:01:14.147 BYG [38204:207]清单项目名称:{(   )}   2011-02-21 18:01:14.147 BYG [38204:207]清单项目已检查:是的!

其中两个项目(清单名称和清单项目名称)只返回空括号。我想我对这是为什么有一个模糊的理解:这两个属性是在多对多的关系中,所以它不知道它应该告诉我哪个核对清单的名称。如何获取这些对象的值?

很抱歉,如果这个解释是模糊的。经过一天努力解决后,我的大脑已经关闭了很多次。)

--------------------------编辑------

感谢您的帮助!我修改了我的代码,它似乎工作!如果你能告诉我这一切是否好看,或者我是否犯了任何菜鸟错误,我将不胜感激:

   - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    

    // Override point for customization after application launch.   
    // TEST CORE DATA - MAKE OBJECTS
    NSManagedObjectContext *context = [self managedObjectContext];

    Trip *newTrip = [Trip addEntityForContext:context];
    newTrip.tripName = @"Test Trip with addEntity"; 

    Checklist *newChecklist = [NSEntityDescription insertNewObjectForEntityForName:@"Checklist" inManagedObjectContext:context];
    [newTrip addChecklistsObject:newChecklist];
    newChecklist.checklistName = @"Test Checklist"; 

    ChecklistItem *newChecklistItem = [NSEntityDescription insertNewObjectForEntityForName:@"ChecklistItem" inManagedObjectContext:context];
    [newChecklist addChecklistItemsObject:newChecklistItem];
    newChecklistItem.checklistItemName = @"Test Checklist Item";
    newChecklistItem.checklistItemChecked = [NSNumber numberWithBool:TRUE];

    NSError *error;
    if (![context save:&error]) {
        NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
    }

    // TEST CORE DATA - LIST OBJECTS
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setEntity:[NSEntityDescription entityForName:@"Trip" inManagedObjectContext:context]];    
    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
    for (Trip *info in fetchedObjects) {
        NSLog(@"Trip Name: %@", info.tripName);

        NSSet *aChecklistSet = [[NSSet alloc]initWithSet:info.checklists];
        Checklist *aChecklist = [aChecklistSet anyObject];
        NSLog(@"Checklist Name: %@", aChecklist.checklistName);

        NSSet *aChecklistItemSet = [[NSSet alloc]initWithSet:aChecklist.checklistItems];
        ChecklistItem *aChecklistItem = [aChecklistItemSet anyObject];
        NSLog(@"Checklist Item Name: %@", aChecklistItem.checklistItemName);
        NSLog(@"Checklist Item Checked: %@", aChecklistItem.checklistItemChecked ? @"Yes it is!" : @"No It's Not!");
    }
    [fetchRequest release];

    [self.window makeKeyAndVisible];

    return YES;
}

(我还没有实现addEntity,因为我不确定模型对象如何抓住Context,但我认为这只是一个代码整洁的事情,所以我还没有担心它。) / p>

1 个答案:

答案 0 :(得分:2)

你自己很难。你必须制作(模型)类。如果您不知道模型,请参阅:
MVC

您可以执行此操作转到您的coredatamodel,单击模型(不在实体上)并从文件菜单中选择新建。在这里,您可以选择创建NSManagedObject子类。这将为您选择的实体创建类。

这些类代表您的核心数据对象。

尝试在所有类中实现静态方法:

+ (CheckListItem *) addEntity {
   return (CheckListItem *)[NSEntityDescription insertNewObjectForEntityForName:@"ChecklistItem" inManagedObjectContext:context];
}

对于上下文,您可以做两件事。 1)从您的应用程序设置上下文:didFinishLaunchingWithOptions: 2)使单例实例保存您的上下文。 (更好的解决方案)

您现在可以轻松地从您的应用程序调用完成启动:

CheckListItem *newItem = [CheckListItem addEntity];
CheckList *newList = [CheckList addEntity];

newItem.name = @"MyCheckListItemName";
newList.name = @"MyListName";

对于你可以做的关系:

newItem.checkList = newList;

或者:

[newList addCheckListItemsObject:newItem];