尝试使用 JSON 填充核心数据结构,
代码在下面列出?
NSManagedObjectContext *context = managedObjectContext();
// Save the managed object context
NSError *error = nil;
if (![context save:&error]) {
NSLog(@"Error while saving %@", ([error localizedDescription] != nil) ? [error localizedDescription] : @"Unknown Error");
exit(1);
}
NSError* err = nil;
NSString* dataPath = [[NSBundle mainBundle] pathForResource:@"Exercises" ofType:@"json"];
NSArray* Exercises = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath]
options:kNilOptions
error:&err];
NSLog(@"Imported Exercises: %@", Exercises);
NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:@"Exercise" inManagedObjectContext:context];
NSString *theJSONString = @"{\"key\":\"value\"}";
NSError *theError = NULL;
NSDictionary *jsonDict = [NSDictionary dictionaryWithJSONString:theJSONString error:&theError];
Exercise *exercise = [NSEntityDescription insertNewObjectForEntityForName:@"Exercise"
inManagedObjectContext:context];
[Exercises enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSDictionary *attributes = [[object entity] attributesByName];
for (NSString *attribute in attributes) {
id value = [jsonDict objectForKey:attribute];
if (value == nil) {
continue;
}
[exercise setValue:value forKey:attribute];
}
NSError *error;
if (![context save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
}];
代码编译并分析创建的 sqlite 数据库后,所有属性都填充为空值。
NSString* secondDataPath = [[NSBundle mainBundle] pathForResource:@"Weights" ofType:@"json"];
NSArray* weightsFromJSON = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:secondDataPath]
options:kNilOptions
error:&err];
NSLog(@"Imported weightsFromJSON: %@", weightsFromJSON);
[weightsFromJSON enumerateObjectsUsingBlock:^(NSDictionary *weightDictionary, NSUInteger idx, BOOL *stop) {
Weight *weight = [NSEntityDescription insertNewObjectForEntityForName:@"Weight"
inManagedObjectContext:context];
NSDictionary *attributes = [[weight entity] attributesByName];
for (NSString *attribute in [attributes allKeys]) {
id value = [weightDictionary objectForKey:attribute];
if (value == nil) {
continue;
}
[weight setValue:value forKey:attribute];
}
NSError *error;
if (![context save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
}];
为第二个实体编辑了上面的代码,但未能说明数据参数是 hill