问题
I think this is wrong, it only loads one car part: This methods takes two arrays one with car names, one with parts, creates a new car, and adds car parts to it, then saves the car to core data. (currently does not work this way)
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];
}
回答1:
I know what's going on here.
You need to insert a new part object into core data for each part. As it is right now, you are only making one part object and then overwriting it inside the for loop. Your code should look something akin to this...
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];
As I said in my above comment, I suggest moving the save to outside the loops.
Another suggestion for easier to read code. When enumerating an array in a simple for loop try something like...
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.
*/
}
来源:https://stackoverflow.com/questions/14127690/issue-loading-subentities-to-mangedobject-in-coredata