我知道有很多與此主題相關的問題,但我似乎無法找到解答我的問題的問題!與iOS核心數據的多對多關係
我有一個這樣的資料單和圖像之間的關係:
我解析內部JSON文件(僅一次),以將數據導入到核心數據。
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專家!)。
我想我的問題是:我正確地將對象插入到核心數據中,只是在我試圖將其打印出來時錯誤 - 或 - 應該以不同方式將對象存儲到核心數據中嗎?
謝謝!
謝謝,這是做到了。當Core Data在我的頭文件中自動生成NSSet時,我認爲這是一組圖像並稱爲「NSSet *圖像」,所以我將其作爲複數形式,這讓人感到困惑。我想這足以混淆Xcode!在h文件中將其改回單數解決了我的問題。 – monalisa717