【问题标题】:Retrieving NSImage from CoreData - Mac OS X从 CoreData 检索 NSImage - Mac OS X
【发布时间】:2012-12-28 07:26:24
【问题描述】:

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

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

【问题讨论】:

    标签: macos core-data nsfetchrequest nsimage


    【解决方案1】:

    错误在这一行

    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;
    }
    

    【讨论】:

    • 我最终得到这个错误:警告 - 试图解码 NSCGSImageRep 2012-12-28 16:00:01.868 The Template[10703:503] *** -[__NSArrayI objectAtIndex:]: index 0超出空数组的界限当我执行 [array count] 的 NSLog 时,我得到的答案是 5 或某个数字。
    • @DesperateLearner:我已将答案中的代码分成多行。您究竟在哪一行得到了异常?
    • @DesperateLearner:我已经测试了代码,可以成功保存和加载NSImage,所以应该是正确的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-02
    • 1970-01-01
    • 1970-01-01
    • 2010-10-23
    • 1970-01-01
    • 2011-01-13
    • 2017-07-30
    相关资源
    最近更新 更多