【问题标题】:How to link existing values in a 1 to many relationship in core data?如何在核心数据中以一对多关系链接现有值?
【发布时间】:2011-06-16 18:01:40
【问题描述】:

我正在尝试将已在类别中的值链接到 wod 实体。因为我确实想为每个类别的 wod 记录调用一个新记录。不知道该怎么做。我正在考虑使用谓词,但我不确定如何将它与获取请求链接。

这是我的架构的样子:

这是试图将它们链接在一起的代码:

 NSManagedObjectContext *context = [self managedObjectContext];
    Wod *wodInfo = [NSEntityDescription
                                       insertNewObjectForEntityForName:@"Wods" 
                                       inManagedObjectContext:context];
    [wodInfo setValue:@"Frank" forKey:@"name"];


    NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
    [request setEntity:[NSEntityDescription entityForName:@"Categories"
                                   inManagedObjectContext:context]];
    [request setPredicate:[NSPredicate predicateWithFormat:@"(name == %@", @"Time"]];

    // This is the part where i am unsure, since i am not exactly sure how to link them up
      Category *category = reques
      wodInfo.category = 



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

任何帮助将不胜感激。

【问题讨论】:

    标签: iphone core-data nsmanagedobjectcontext nsfetchrequest


    【解决方案1】:
    NSError *error = nil;
    NSArray *categories = [context executeFetchRequest:request error:&error];
    Category *category = [categories lastObject];
    wodInfo.category = category;
    

    请谨慎拨打[context save:&error]。您正在传递错误变量的地址,该变量未在您的代码中初始化,并且将引用一个随机地址,这可能会导致您的应用程序出现奇怪的错误。我建议在将其传递给 save: 方法之前将其设置为 nil。

    【讨论】:

    • 似乎当我添加类别并尝试访问该数据时。它返回给我一个 NSFaultingMutableSet 不应该是类别吗?
    • 我是否正确理解您希望每个 wod 都属于一个类别并且您允许多个 wods 属于一个类别?
    • 如果是这样,那么我相信您可能已经定义了相反方向的一对多关系。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-02
    • 1970-01-01
    相关资源
    最近更新 更多