从CoreData检索NSImage - Mac OS X.

时间:2012-12-28 07:26:24

标签: macos core-data nsfetchrequest nsimage

我正在尝试将图像添加到核心数据中并在需要时加载它。我目前正在将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];

缩略图是实体名称,我在缩略图实体下有两个属性 - fileName(NSString)和image(id - transformable)。

我正试图按照以下方式检索它们:

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.

图像已添加但无法检索 关于如何解决这个问题的任何想法?我做得对吗?

1 个答案:

答案 0 :(得分: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;
}