0

我正在尝试将图像添加到核心数据中并在需要时加载它。我目前正在将 NSImage 添加到核心数据中,如下所示:

Thumbnail *testEntity = (Thumbnail *)[NSEntityDescription insertNewObjectForEntityForName:@"Thumbnail" inManagedObjectContext:self.managedObjectContext];
NSImage *image = rangeImageView.image;
testEntity.fileName = @"test";
testEntity.image = image;
NSError *error;
[self.managedObjectContext save:&error];

Thumbnail 是实体名称,我在 Thumbnail 实体下有两个属性 - 文件名(NSString)和图像(id - 可转换)。

我正在尝试按如下方式检索它们:

NSManagedObjectContext *context = [self managedObjectContext];

NSFetchRequest * fetchRequest = [[NSFetchRequest alloc] init];

NSEntityDescription *imageEntity = [NSEntityDescription entityForName:@"Thumbnail" inManagedObjectContext:[context valueForKey:@"image"]];

[fetchRequest setEntity:imageEntity];

NSError *error;

NSArray * array = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];

if (array == nil) {

    NSLog(@"Testing: No results found");

}else {



   _coreDataImageView.image = [array objectAtIndex:0];
}

我最终得到这个错误:

     [<NSManagedObjectContext 0x103979f60> valueForUndefinedKey:]: this class is not key value coding-compliant for the key image.

图像已添加但无法检索。
关于如何进行此操作的任何想法?我做对了吗?

4

1 回答 1

3

错误在这一行

NSEntityDescription *imageEntity = [NSEntityDescription entityForName:@"Thumbnail"
          inManagedObjectContext:[context valueForKey:@"image"]];

您不能应用于valueForKey:@"image"托管对象上下文。您必须将其应用于获取的对象(或使用获取的对象的image属性)。

另请注意,仅在发生错误时才executeFetchRequest:返回。nil如果没有找到实体,则返回一个空数组。

NSEntityDescription *imageEntity = [NSEntityDescription entityForName:@"Thumbnail" inManagedObjectContext:context];
[fetchRequest setEntity:imageEntity];

NSError *error;
NSArray * array = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (array == nil) {
    NSLog(@"Testing: Fetch error: %@", error);
} else if ([array count] == 0) {
    NSLog(@"Testing: No results found");
}else {
   Thumbnail *testEntity = [array objectAtIndex:0];
   NSImage *image = testEntity.image;
   _coreDataImageView.image = image;
}
于 2012-12-28T07:46:32.750 回答