【发布时间】:2014-01-10 04:17:07
【问题描述】:
我知道在 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 专家!)。
我想我的问题是:我是否正确地将对象插入到核心数据中,并且在尝试将其打印回来时只是不正确--或者--,我应该以不同的方式将对象存储到核心数据中吗?
谢谢!
【问题讨论】:
标签: ios iphone objective-c core-data