Question

I have an entity type in my Core Data managed object context called Event that has a one-to-many relationship to another entity called Activity. That is, each event can have many activities.

In my app's AddNewEvent method I do the following:

// create the first default itinerary activity object (Ceremony)
NSManagedObject *newActivity = [NSEntityDescription insertNewObjectForEntityForName:@"Activity" inManagedObjectContext:context];
[newActivity setValue:@"Ceremony" forKey:@"activityName"];
[newActivity setValue:[NSDate date] forKey:@"activityDate"];
[newActivity setValue:@"" forKey:@"activityNotes"];
[newActivity setValue:@NO forKey:@"complete"];
[newActivity setValue:@NO forKey:@"hidden"];
[newActivity setValue:@"" forKey:@"venueAddress"];
[newActivity setValue:@"" forKey:@"venueBusinessPhone"];
[newActivity setValue:@"" forKey:@"venueContact"];
[newActivity setValue:@"" forKey:@"venueEmail"];
[newActivity setValue:@"" forKey:@"venueName"];
[newActivity setValue:@"" forKey:@"venueWebsite"];

NSLog(@"new activity name: %@", [newActivity valueForKey:@"activityName"]); // test 1

NSMutableSet *newActivitiesSet;
[newActivitiesSet addObject:newActivity];

NSMutableArray *newActivitiesArray = [[newActivitiesSet allObjects] mutableCopy];
NSLog(@"new activity name in set: %@", [[newActivitiesArray objectAtIndex:0] valueForKey:@"activityName"]); // test 2

// finally, add activities to the Event object
[newEvent setValue:newActivitiesSet forKey:@"activities"];

Perhaps I'm not handling the set/array properly, but when I log the name of the Activity in the line commented "test 1" it prints "Ceremony" correctly. However, when I log it in the line commented "test 2" it prints "(null)". It seems that the Activity object is not getting added to the set or that the set isn't getting copied into the array properly, or maybe something I'm not thinking of.

Am I handling this whole process correctly with the set, array, and adding the set to the Event object's Activities relationship? (I realize that my two test lines occur before I even save the data out to the context, but that shouldn't matter for the two tests I'm running here.)

Thanks!

Was it helpful?

Solution

You need to instantiate the set.

NSMutableSet *newActivitiesSet = [[NSMutableSet alloc]init];

Edit: Also, I try to avoid using the word "new". Why not call it activity and activitiesSet

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top