开发者

How to link existing values in a 1 to many relationship in core data?

I am trying to link a value that's already in category to the wod entity. Since I do want to call a new record for each record of wod for a category. Not sure how to do this. I was thinking of using predicate but I am not exactly sure how to link it from a f开发者_StackOverflow中文版etch request.

this is what my schema looks like:

How to link existing values in a 1 to many relationship in core data?

Here's the code that tries to link them together:

 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]);
    }

Any help would be greatly appreciated.


NSError *error = nil;
NSArray *categories = [context executeFetchRequest:request error:&error];
Category *category = [categories lastObject];
wodInfo.category = category;

Be careful about your call to [context save:&error]. You are passing the address of the error variable, which is not initialized in your code and will refer to a random address, which might lead to weird errors in your application. I would recommend setting it to nil before passing it to the save: method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜