我知道在SO上有很多与此主题相关的问题,但我似乎找不到能回答我问题的问题!
我在FactSheet和Image之间有一个关系,如下所示:
我正在解析内部JSON文件(只有一次)以将数据导入Core Data。
int main(int argc, const char * argv[])
{
@autoreleasepool {
// 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:@"FactSheets" ofType:@"json"];
NSArray* FactSheets = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath]
options:kNilOptions
error:&err];
[FactSheets enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
FactSheet *factSheet = [NSEntityDescription
insertNewObjectForEntityForName:@"FactSheet"
inManagedObjectContext:context];
factSheet.name = [obj objectForKey:@"name"];
factSheet.details = [obj objectForKey:@"details"];
NSArray* images=[obj objectForKey:@"images"];
[images enumerateObjectsUsingBlock:^(id img, NSUInteger idx, BOOL *stop) {
Image *image = [NSEntityDescription insertNewObjectForEntityForName:@"Image"
inManagedObjectContext:factSheet.managedObjectContext];
image.path = [img objectForKey:@"path"];
if([img objectForKey:@"caption"]!=[NSNull null]) {
image.caption = [img objectForKey:@"caption"];
}
if([img objectForKey:@"label"]!=[NSNull null]) {
image.label = [img objectForKey:@"label"];
}
if([img objectForKey:@"galleryThumb"]!=[NSNull null]) {
image.galleryThumb = [img objectForKey:@"galleryThumb"];
}
[factSheet addImageObject:image];
}];
NSError *error;
if (![context save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
}];
//Test listing
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"FactSheet"
inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
for (FactSheet *fs in fetchedObjects) {
NSLog(@"Name: %@", fs.name);
for (Image *i in fs.images) {
NSLog(@"Image Path: %@",i.path);
}
}
}
return 0;
}
运行此工作直到我尝试使用NSLog打印出来。它打破了以下几行:
for (Image *i in fs.images) {
使用“无法识别的选择器发送到实例”错误。当我在SQLite数据库浏览器中打开.sqlite文件时,似乎已经插入了数据,我认为应该如何(尽管我不是SQLite专家!)。
我想我的问题是:我是否正确地将对象插入到核心数据中并且在尝试将其打印出来时不正确 - 或者 - 我是否应该以不同的方式将对象存储到核心数据中?
谢谢!
答案 0 :(得分:1)
将通话更改为:
for (Image *i in fs.image) {
根据您的模型,关系名称为image
,因此您可以更新模型或循环代码。
答案 1 :(得分:0)
尝试 - for(Image * i in fs.image){ 请注意,它应该是fs.image而不是fs.images。