Issue loading subentities to mangedobject in coredata

…衆ロ難τιáo~ 提交于 2019-12-11 16:52:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!