![](/img/trans.png)
[英]iOS Core Data error - Unacceptable type of value for to-many relationship
[英]To-Many Relationship with iOS Core Data
我知道有很多与此主题相关的问题,但是我似乎找不到能回答我问题的问题!
我在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专家!)。
我猜我的问题是:我是否正确地将对象插入核心数据中,并且尝试打印出来是不正确的?或者,是否应该以其他方式将对象存储到核心数据中?
谢谢!
将呼叫更改为: for (Image *i in fs.image) {
根据您的模型,关系名称为image
因此您可以更新模型或循环代码。
尝试使用-for(fs.image中的Image * i){注意,它应该是fs.image而不是fs.images。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.