coder
coder

Reputation: 10520

Problems saving a to-many relationship in Core Data

I've been trying to implement Core Data into my application, and most recently, trying to set a to-many relationship. I set the relationship below

NSMutableSet *todoObjects = [[NSMutableSet alloc] init];
for (int i = 0; i < [allTodolistsData count]; i++) {
    NSDictionary *dictionary = [allTodolistsData objectAtIndex:i];
    TodolistObject *tempTodolist = [[TodolistObject alloc] initWithDict:dictionary];
    [todoObjects addObject:[Todolists newTodolist:tempTodolist withContext:appDelegate.context]];
    [tempTodolist release];
}

[project setTodolists:todoObjects];

The project variable is an NSManagedObject, and the setTodolists: method is auto-generated to set the to-do lists for the project. Since the project has a to-many relationship with the set of to-do lists, I pass in an NSMutableSet. When I do this, however, I get the following error:

-[__NSArrayM isEqualToSet:]: unrecognized selector sent to instance 0xa325d60

I can't seem to find anyone who has had this problem. Any ideas?

Upvotes: 0

Views: 170

Answers (1)

Matt Long
Matt Long

Reputation: 24466

You have to get the mutable set for the relationship back from your NSManagedObject and add your new objects to it, thusly:

NSMutableSet *todoObjects = (NSMutableSet*)[project mutableSetValueForKey:@"todoLists"];

// Switch your for loop to use fast-enumaration
for (NSDictionary *dictionary in allTodolistsData) {
    TodolistObject *tempTodolist = [[TodolistObject alloc] initWithDict:dictionary];
    [todoObjects addObject:[Todolists newTodolist:tempTodolist withContext:appDelegate.context]];
    [tempTodolist release];
}

// Save project in the same context where you created the object

Upvotes: 1

Related Questions