通过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数据库后,我实现的是,Strength有3次锻炼,Core有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]);
}
}];
请轻松,我是新手。在代码中我添加了评论,我认为我可能犯了错误。
将不胜感激任何帮助。谢谢。