0

我认为这是错误的,它只加载一个汽车零件:此方法采用两个数组,一个带有汽车名称,一个带有零件,创建一辆新汽车,并将汽车零件添加到其中,然后将汽车保存到核心数据中。(目前不以这种方式工作)

for (int i=0; i<[massiveArray count]; i++) {
    //create a new car and part
        Car*newCar =(Car*)[NSEntityDescription insertNewObjectForEntityForName:@"Car" inManagedObjectContext:[self managedObjectContext]];
        CarPart *part =[NSEntityDescription insertNewObjectForEntityForName:@"CarPart" inManagedObjectContext:[self managedObjectContext]];

//set car title to string title in array of titles
        [newCar setValue:[massiveArray objectAtIndex:i] forKey:@"name"];
        //go through car parts array and add all new parts for that specific car
        for (int i=0; i<[partNamesArray count]; i++) {
            [part setValue:[partNamesArray objectAtIndex:i] forKey:@"name"];
            [newCar addToCarPartObject:part];
//save each part??? I think this is wrong
            [self.managedObjectContext save:nil];
        }
//Save new car
        [self.managedObjectContext save:nil];
    }
4

1 回答 1

2

我知道这里发生了什么。

您需要将新的零件对象插入到每个零件的核心数据中。就像现在一样,您只制作一个部分对象,然后在 for 循环中覆盖它。您的代码应该类似于此...

for (int i=0; i<[massiveArray count]; i++) {
    //create a new car and part
    Car *newCar = [NSEntityDescription insertNewObjectForEntityForName:@"Car" inManagedObjectContext:[self managedObjectContext]];

    //set car title to string title in array of titles
    [newCar setValue:[massiveArray objectAtIndex:i] forKey:@"name"];

    //go through car parts array and add all new parts for that specific car
    for (int i=0; i<[partNamesArray count]; i++) {
        CarPart *part =[NSEntityDescription insertNewObjectForEntityForName:@"CarPart" inManagedObjectContext:[self managedObjectContext]];
        [part setValue:[partNamesArray objectAtIndex:i] forKey:@"name"];
        [newCar addToCarPartObject:part];
    }
}
//Save the entire context (all pending changes to cars and their parts)
[self.managedObjectContext save:nil];

正如我在上面的评论中所说,我建议将保存移到循环之外。

另一个更容易阅读代码的建议。在简单的 for 循环中枚举数组时,尝试类似...

for (NSString *carTitle in massiveArray) {
    /* Now do your stuff in here... 'carTitle' will be different during 
     * each pass of the loop. No need to increment an i variable or grab 
     * the object from the array on each pass. 
     */
}
于 2013-01-02T19:25:08.487 回答