通过 JSON 填充一对多核心数据模型时遇到问题。
背景:
Two Entities:
WorkoutType
Attributes:
-workoutType
Relationship: workouts
Destination: WorkoutSet
Inverse: workoutType
WorkoutSet
Attributes:
-workoutName
Relationship: workoutType
Destination: WorkoutType
inverse: workouts
下面是我的 JSON:
[
{ "workoutType": "Strength",
"workouts":
[ { "workoutName": "Strength 1"},
{ "workoutName": "Strength 2"},
{ "workoutName": "Strength 3"},
{ "workoutName": "Strength 4"}
],
},
{ "workoutType": "Core",
"workouts":
[ { "workoutName": "Core 1"},
{ "workoutName": "Core 2"},
{ "workoutName": "Core 3"},
{ "workoutName": "Core 4"}
],
}
]
JSON 解析正确,问题是对于每个 WorkoutType(核心和力量)应该有 4 次锻炼(力量 1,力量 2,......)..(核心 1,核心 2,......)。
在查看创建的 sqlite 数据库后,我实现的是力量有 3 次锻炼,核心有 5 次锻炼。每次我编译代码时,数字都会改变。
我正在使用的代码如下:
NSString* thirdDataPath = [[NSBundle mainBundle] pathForResource:@"Workouts" ofType:@"json"];
NSArray* Workouts = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:thirdDataPath]
options:kNilOptions
error:&err];
NSLog(@"Imported Workouts: %@", Workouts);
[Workouts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
WorkoutType *workoutType = [NSEntityDescription
insertNewObjectForEntityForName:@"WorkoutType"
inManagedObjectContext:context];
workoutType.workoutType = [obj objectForKey:@"workoutType"];
NSArray *workoutsArray = [obj objectForKey:@"workouts"];
[workoutsArray enumerateObjectsUsingBlock:^(id workoutsObj, NSUInteger workoutsIdx, BOOL *workoutsStop) {
WorkoutSet *workoutSet = [NSEntityDescription
insertNewObjectForEntityForName:@"WorkoutSet"
inManagedObjectContext:context];
//Not Sure if the line below is correct, also not sure if i should be setting the relationship here too something like workoutSet.workouts = ....
workoutSet.workoutType = workoutType;
workoutSet.workoutName = [workoutsObj objectForKey:@"workoutName"];
}];
NSError *error;
if (![context save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
}];
请放轻松,我是新手。在代码中,我添加了一条评论,我认为我可能犯了错误。
将不胜感激任何帮助。谢谢你。