0

我一直在尝试将 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

我似乎找不到遇到这个问题的人。有任何想法吗?

4

1 回答 1

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
于 2012-10-23T05:06:53.213 回答