Mark
Mark

Reputation: 113

Core data and multiple entites

Having a really hard time grasping the way core data works, and I'm hoping I can get some very basic help here.

I have two entities:

Profiles<-->>Events

I have successfully figured out how to add profiles, view profiles in table view and view events for a profile in a table view via a predicate fetch.

Now, here is where I am lost. Lets say I want to update an event in the Event entity. Do I have to do a fetch with predicate to create a Profiles object before I update the Event entity? Or can I just update the Event entity and somehow tell it which Profile it is associated with via the relationship?

Here is where I have hit the log jam:

// add new event
    //NSLog(@"Adding New Event");

    NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Events"];
    NSPredicate *predicate=[NSPredicate predicateWithFormat:@"ANY profile.profilename=[cd] %@",[self profilename]];

    [fetchRequest setPredicate:predicate];

    self.events = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];

    //insert event info
    NSManagedObject *eventInfo = [NSEntityDescription insertNewObjectForEntityForName:@"Events" inManagedObjectContext:self.managedObjectContext];


/////////  THIS IS WHERE I NEED HELP



}


// save the context
NSError *error = nil;
if (![managedObjectContext save:&error]){
    NSLog(@"Error! %@",error);
}

I'm about ready just to create a flat file and work with that! It's driving me nuts!

EDIT - CHANGED CODE BELOW ***********************

// add new event
    //NSLog(@"Adding New Event");

    Events *newEvent = (Events *)[NSEntityDescription insertNewObjectForEntityForName:@"Events" inManagedObjectContext:managedObjectContext];
    newEvent.eventdesc=self.eventDescTextField.text;


    NSString *wkst = eventDescTextField.text;
    NSNumber  *wk = [NSNumber numberWithInteger: [wkst integerValue]];
    newEvent.weeksout = wk;

So now I know I need to tell the Event entity to use the current profile..how do I access the relationship?

Upvotes: 1

Views: 77

Answers (1)

Abizern
Abizern

Reputation: 150715

Looking at the code you've provided, I think you have a misconception about Core Data.

It looks like you are trying to get all the events related to a profile. You don't need to create ond perform a fetch request for this. Core Data is an object graph. Which means that if you have an object in an a managed object context, you get its related objects via it's relationships, you don't need to run a fetch request.

Upvotes: 1

Related Questions