我已设法通过JSON文件预先填充核心数据模型,该模型由一个具有许多属性的实体组成。
然后我添加了第二个实体,并在使用相同的JSON文件预先填充此实体时遇到了问题,所以我想我会创建另一个JSON文件来预先填充第二个实体,但这似乎没有用。< / p>
以下代码是我尝试使用的代码:
//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]);
}
}];
将不胜感激任何帮助。谢谢
答案 0 :(得分:0)
Cocoa提供了一种方法,使这更加简单。由于键值编码,NSObject中有一种方法可以将上述内容简化为单行
[myObj setValuesForKeysWithDictionary:jsonDict];
这将在jsonDict中运行键/值对,并在myObj上设置相同的键/值对