在Core Data中保存多对多关系的问题

时间:2012-10-22 19:46:31

标签: iphone objective-c ios core-data

我一直在尝试将Core Data应用到我的应用程序中,最近,我试图建立一个多对多的关系。我在下面设置了关系

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];

项目变量是NSManagedObject,并且会自动生成setTodolists:方法来设置项目的待办事项列表。由于项目与待办事项列表具有多对多的关系,因此我传入一个NSMutableSet。但是,当我这样做时,我收到以下错误:

- [__ NSArrayM isEqualToSet:]:无法识别的选择器发送到实例0xa325d60

我似乎找不到有这个问题的人。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

你必须从NSManagedObject获取关系的可变集并将新对象添加到它,因此:

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