我已经设法通过 JSON 文件预先填充了一个核心数据模型,该模型由一个具有许多属性的实体组成。
然后我添加了第二个实体,并在使用相同的 JSON 文件预填充这个实体时遇到了问题,所以我想我会创建另一个 JSON 文件来预填充第二个实体,但这似乎不起作用。
下面的代码是我尝试使用的:
//Below is the code for the first entity
NSString* dataPath = [[NSBundle mainBundle] pathForResource:@"Exercises" ofType:@"json"];
NSArray* Exercises = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath]
options:kNilOptions
error:&err];
NSLog(@"Imported Exercises: %@", Exercises);
[Exercises enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
Exercise *exercise = [NSEntityDescription
insertNewObjectForEntityForName:@"Exercise"
inManagedObjectContext:context];
exercise.tag = [obj objectForKey:@"tag"];
exercise.name = [obj objectForKey:@"name"];
exercise.type = [obj objectForKey:@"type"];
NSError *error;
if (![context save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
}];
//Below is the code for the second Entity
dataPath = [[NSBundle mainBundle] pathForResource:@"Weights" ofType:@"json"];
//Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'
NSArray* Weights = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath]
options:kNilOptions
error:&err];
NSLog(@"Imported Weights: %@", Weights);
[Weights enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
Weight *weight = [NSEntityDescription
insertNewObjectForEntityForName:@"Weight"
inManagedObjectContext:context];
weight.weight = [obj objectForKey:@"weightEntry"];
NSError *error;
if (![context save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
}];
将不胜感激任何帮助。谢谢你