循环通过ManagedObject

时间:2014-02-04 17:28:33

标签: objective-c

我正在尝试将NSMutableArray添加到我的newManagedObject中。问题是它似乎在我的theLanguage数组中插入了两次相同的对象而不是两个对象。

这是我的代码:

theLanguage =[NSMutableArray arrayWithObjects: nil];
[theLanguage addObject:@[@"Danish", @""]];
[theLanguage addObject:@[@"Russian", @""]];


AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
_managedObjectContext = delegate.managedObjectContext;

newManagedObject = (Language*)[NSEntityDescription insertNewObjectForEntityForName:@"Language" inManagedObjectContext:_managedObjectContext];

for (int i = 0; i <= theLanguage.count-1; i++)
{
    [newManagedObject setValue:theLanguage[i][0] forKey:@"LanguageName"];
}

theLanguage阵列的输出是丹麦语,俄语 newManagedObject的输出是丹麦语,丹麦语。我做错了什么?

1 个答案:

答案 0 :(得分:0)

您好像应该插入2 Language个实体,或者需要将LanguageName的值设置为数组。循环theLanguage并在同一个newManagedObject上调用setValue:forKey:方法将覆盖任何现有值。

我认为你真的想要做以下事情:

for (NSArray *language in theLanguage)
{
    Language *newManagedObject = (Language *)[NSEntityDescription insertNewObjectForEntityForName:@"Language" inManagedObjectContext:_managedObjectContext];
    [newManagedObject setValue:language[0] forKey:@"LanguageName"];
}