CoreData:是否将图像存储到数据库? [英] CoreData : store images to DB or not?

查看:21
本文介绍了CoreData:是否将图像存储到数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个应用程序,它可以从网站上为某个用户名拍摄照片,并使用用户名将其显示在 UITable 中,然后单击用户名时,它会显示该用户的照片,然后单击照片名称,它会显示全屏照片.

I am making an app that takes photos from web site for some Username and shows it in a UITable with username then when clicking user name it shows photos for this user and then clicking to name of photo it shows full screen photo.

我的问题是我正在使用 NSData 从互联网上获取照片.我是否必须将数据保存到 CoreData?当按下用户名时,它会创建 NSData 并从互联网下载照片并将它们显示在 UITable 上.这需要时间.

My question is I am using NSData to get photos from internet. Do I have to save the data to CoreData? When pressing name of user it creates NSData and downloads photos from internet and shows them on UITable. And it takes time.

什么是好的方法?以及如何将这些图像保存到 CoreData?

What is good approach? and How can save this images to CoreData?

我正在使用这种方法

NSData *imageData=[flickr dataForPhotoID:firstPhoto.id fromFarm:firstPhoto.farm 
onServer:firstPhoto.server withSecret:firstPhoto.secret inFormat: 
FlickrFetcherPhotoFormatSquare];

这里定义了 dataForPhotoID 方法

and here definition of dataForPhotoID method

- (NSData *)dataForPhotoID:(NSString *)photoID fromFarm:(NSString *)farm   
   onServer:(NSString *)server withSecret:(NSString *)secret 
 inFormat:(FlickrFetcherPhotoFormat)format {

#if TEST_HIGH_NETWORK_LATENCY
sleep(1);
#endif

NSString *formatString;

switch (format) {
    case FlickrFetcherPhotoFormatSquare:    formatString = @"s"; break;
    case FlickrFetcherPhotoFormatLarge:     formatString = @"b"; break;
}

NSString *photoURLString = [NSString stringWithFormat:@"http://farm%@.static.flickr.com/%@/%@_%@_%@.jpg", farm, server, photoID, secret, formatString];
NSURL *url = [NSURL URLWithString:photoURLString];

return [NSData dataWithContentsOfURL:url];
}

推荐答案

首先,始终以可用的格式存储图像,例如 PNG 或 JPEG,而不是 NSData.这将为您省去很多麻烦.

First, always store your images in a usable format such as PNG or JPEG instead of NSData. This will save you a lot of headaches.

其次,存储二进制数据的规则是:

Second, the rule for storing binary data is:

  • <100kb 与相关数据存储在同一张表中
  • <1mb 存储在通过关系附加的单独表中,以避免不必要的加载

1mb 存储在磁盘上并在核心数据中引用它

1mb store on disk and reference it inside of Core Data

Core Data 内部的存储应该是二进制的,你可以为它编写访问器方法.看看这个答案:Core data images from desktop to iphone

The storage inside of Core Data should be binary and you can write accessor methods for it. Take a look at this answer: Core data images from desktop to iphone

我链接的示例代码描述了如何在您的 NSManagedObject 子类中创建访问器,以在 UIImage 和二进制数据之间来回转换图像.

The example code I linked to describes how to create accessors in your NSManagedObject subclass that will convert the image back and forth between a UIImage and binary data.

这篇关于CoreData:是否将图像存储到数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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