Need help with many-to-many relationships in core data for iPhone

前端 未结 4 1497
抹茶落季
抹茶落季 2021-02-09 19:21

I have come to a roadblock in my current project. I basically have an app that is much like the Core Data Recipe app... Here is the basic structure I have in my .xcdatamodel

4条回答
  •  离开以前
    2021-02-09 19:28

    OK, After working on this for the past 2 days I finally came up with my solution which was actually a mix between Alex and Wills suggestions... Thank you to both of you!!

    Here is what I have...

     NSManagedObjectContext *context = [restaurant managedObjectContext];
    
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setEntity:[NSEntityDescription entityForName:@"Category" inManagedObjectContext:context]];
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:&sortDescriptor count:1];
    [fetchRequest setSortDescriptors:sortDescriptors];
    
    NSError *error = nil;
    NSArray *possibleCategories = [context executeFetchRequest:fetchRequest error:&error];
    
    categoryArray = [[NSMutableArray alloc] initWithArray:possibleCategories];
    
    currentCategories = [restaurant valueForKeyPath:@"categories"];
    
    [restaurant addCategoriesObject:(Category *)[possibleCategories objectAtIndex:15 ]];
    
    [currentCategories addObject:(Category*)[categoryArray objectAtIndex:15]];
    

    and then I save like this

    - (void)save{
        NSLog(@"EditCatagoriesTableViewController - save");
    
        NSSet* myCategorySet = [[NSSet alloc] initWithSet:currentCategories];
    
        NSError *error = nil;
    
        [restaurant addCategories:myCategorySet];
    
    
        error = nil;
        if (![restaurant.managedObjectContext save:&error]) {
            // Handle error
            NSLog(@"restaurant - Unresolved error %@, %@", error, [error userInfo]);
            exit(-1);  // Fail
        }       
    }
    

    And that does it!

    Thank you so much for the help you two!!!

    -Kurt

提交回复
热议问题