我应该如何在我的 Core Data 数据库中存储 UIImages? [英] How should I store UIImages within my Core Data database?

查看:18
本文介绍了我应该如何在我的 Core Data 数据库中存储 UIImages?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个应用程序,需要将大约 100 张或更多图像连同其他相关信息一起预插入到 Core Data 数据库中.

I am developing an application which demands around 100 images or maybe more to be pre-inserted into the Core Data database along with other related information.

现在我只需编写几行代码就可以轻松添加其他数据,但是对于 UIImages,我不确定如何在不编写大量代码的情况下进行添加.我想知道:无论如何,是否可以轻松地做到这一点,或者是否没有以最少的努力实现这一目标的最佳方法.

Now I can easily add other data by just writing a few lines of code but for UIImages I am unsure how to do it without writing a lot of code. I was wondering: is there anyway to do this easily, or if there isn't what's the best way to achieve this with the least amount of effort.

另外,是否可以将图像存储在 Core Data 数据库中,还是应该只将图像的地址保存在本地文件系统中?

Also, is it okay to store images in a Core Data database or should we only only save the addresses of images on the local file system?

推荐答案

在 Core Data 数据库中存储图像非常容易.您只需要将图像属性标记为可转换属性并创建 NSValueTransformer 的子类.在该子类中,添加如下代码:

Storing images within a Core Data database is pretty easy to do. You just need to mark your image attribute as a transformable one and create a subclass of NSValueTransformer. Within that subclass, add code like the following:

+ (Class)transformedValueClass 
{
    return [NSData class]; 
}

+ (BOOL)allowsReverseTransformation 
{
    return YES; 
}

- (id)transformedValue:(id)value 
{
    if (value == nil)
        return nil;

    // I pass in raw data when generating the image, save that directly to the database
    if ([value isKindOfClass:[NSData class]])
        return value;

    return UIImagePNGRepresentation((UIImage *)value);
}

- (id)reverseTransformedValue:(id)value
{
    return [UIImage imageWithData:(NSData *)value];
}

对于您的可转换属性,将此子类的名称指定为值转换器名称.

For your transformable attribute, specify this subclass's name as the Value Transformer Name.

然后,您可以为承载此图像属性的实体创建一个 NSManagedObject 子类,并为此图像属性声明一个属性:

You can then create an NSManagedObject subclass for the entity hosting this image attribute and declare a property for this image attribute:

@property(nonatomic, retain) UIImage *thumbnailImage;

您可以从此属性读取 UIImages 并将 UIImages 写入此属性,并且它们将透明地更改为 NSData 或从 NSData 更改为存储在数据库中.

You can read UIImages from and write UIImages to this property and they will be transparently changed to and from NSData to be stored in the database.

是否执行此操作取决于您的具体情况.较大的图像可能不应该以这种方式存储,或者至少应该在它们自己的实体中,以便在遵循与它们的关系之前它们不会被提取到内存中.以这种方式将小缩略图图像放入数据库可能很好.

Whether or not to do this depends on your particular case. Larger images probably should not be stored in this manner, or at the least should be in their own entity so that they are not fetched into memory until a relationship to them is followed. Small thumbnail images are probably fine to put in your database this way.

这篇关于我应该如何在我的 Core Data 数据库中存储 UIImages?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆