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

前端 未结 4 1531
抹茶落季
抹茶落季 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:29

    You would want to do something like this, instead:

    Restaurant *mcDonalds = (Restaurant *)[NSEntityDescription insertNewObjectForEntityForName:@"Restaurant" inManagedObjectContext:managedObjectContext];
    mcDonalds.name = @"McDonalds";
    
    Restaurant *inNOut = (Restaurant *)[NSEntityDescription insertNewObjectForEntityForName:@"Restaurant" inManagedObjectContext:managedObjectContext];
    inNOut.name = @"In-N-Out";
    
    Category *driveThru = (Category *)[NSEntityDescription insertNewObjectForEntityForName:@"Category" inManagedObjectContext:managedObjectContext];
    driveThru.name = @"Drive Thru to Go";
    
    Category *sitDown = (Category *)[NSEntityDescription insertNewObjectForEntityForName:@"Category" inManagedObjectContext:managedObjectContext];
    sitDown.name = @"Sit Down and Eat";
    
    // make NSSet* of Category objects
    NSSet *fastFood = [NSSet setWithObjects:driveThru, sitDown, nil];
    
    // set Restaurant instances' categories ("to-many") property
    mcDonalds.categories = fastFood;
    inNOut.categories = fastFood;
    
    // save changes to managedObjectContext...
    NSError *error = nil;
    if ([managedObjectContext save:&error]) {
       // handle save error
    }
    

    You're not instantiating your Category managed object correctly, and you want to learn how to use the accessors. Once you have done that, you will be better able to learn how to do fetches.

    Honestly, I would recommend putting your project to the side and going through the Core Data Tutorial for iPhone.

提交回复
热议问题