谁能帮助找出我在这段代码中做错了什么?试图通过 JSON 文件填充核心数据结构
// Create the managed object context
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]);
}
}];
已编辑:代码现在可以编译,但我在核心数据模型中得到空值。谢谢