为什么这只将数组中的最后一个值插入到核心数据中

时间:2014-12-08 04:23:35

标签: ios objective-c core-data

NSLog说它成功地添加了一切 但是当我运行此代码时,只会添加数组中的最后一个值。 任何帮助都表示赞赏,并提前感谢。

exercise = [NSEntityDescription insertNewObjectForEntityForName: @"Exercises" inManagedObjectContext: _managedObjectContext];

for (int i = 0; i < [exerciseNames count]; i++)
{
    [exercise setValue:exerciseNames[i] forKey:@"exerciseName"];
    [exercise setValue:exerciseVids[i] forKey:@"exerciseVid"];
    [exercise setValue:machineNames[i] forKey:@"machineName"];
    [exercise setValue:requiresMachine[i] forKey:@"requiresMachine"];
    [exercise setValue:targets[i] forKey:@"target"];
    NSError *error = nil;
    if([_managedObjectContext save: &error])
    {
        NSLog([@"Successfully added " stringByAppendingString:exerciseNames[i]]);
    }
}

我知道这一点,因为当我运行它时,它只打印出数组中的最后一个值而不是所有

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
                               entityForName:@"Exercises" inManagedObjectContext: managedObjectContext];
[fetchRequest setEntity:entity];
NSError *error = nil;
NSArray *fetchedObjects = [managedObjectContext executeFetchRequest:fetchRequest error:&error];

for (NSManagedObject *info in fetchedObjects) {
    NSLog(@"Exercise Name: %@", [info valueForKey:@"exerciseName"]);
    NSLog(@"Machine Name: %@", [info valueForKey:@"machineName"]);
}

1 个答案:

答案 0 :(得分:1)

也许你的意思是包括这一行:

exercise = [NSEntityDescription insertNewObjectForEntityForName: @"Exercises" inManagedObjectContext: _managedObjectContext];

在你的循环中。由于它在你的循环之外,这意味着你创建了一个练习,但多次写入它。这就是为什么它只有数组最后一个元素的值。将线移动到循环中你应该是好的:)