我该如何保存&使用FMDB将图像(字节)检索到SQLite(blob)? [英] How Can I Save & Retrieve an image (bytes) to SQLite (blob) using FMDB?

查看:178
本文介绍了我该如何保存&使用FMDB将图像(字节)检索到SQLite(blob)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个需要从远程站点(从URL)显示一些图像的iOS应用程序,每当用户进入应该显示图像的屏幕时,应用程序就会冻结,直到下载完成。所以我想将已下载的图像存储到名为COVERS的SQLite表中。

I'm making an iOS App that need to show some images from a remote site (from an URL), and everytime the users enter to the screen that should show the image, the app get freeze until the download is completed. So I want to store the images already downloaded into a SQLite Table named COVERS.

以下是我如何下载和显示图片的代码:

Here is the code that how I'm downloading and Showing the image:

假设movieCover是一个 UIImageView ,对象影片有一个名为cover的 NSURL 属性,其中包含要下载的图片的网址。

Suppose that movieCover is an UIImageView and the object movie has a NSURL property named cover that contains the URL of the image to be downloaded.

NSData *cover = [[NSData alloc] initWithContentsOfURL:movie.cover];
movieCover.image = [[UIImage alloc] initWithData:cover];

但是,我想将其更改为:

But, I want to change it to something like this:

NSData *cover = [appDelegate.dataBase getCoverForMovie:movie];
if( !cover ) {
    cover = [[NSData alloc] initWithContentsOfURL:movie.cover];
    [appDelegate.dataBase setCover:cover ToMovie:movie];
}

movieCover.image = [[UIImage alloc] initWithData:cover];

假设appDelegate是当前ViewController的属性,而dataBase是AppDelegate使用的属性FMDB来操纵DataBase中的数据。

Suppose that appDelegate is a property of the current ViewController, and dataBase is a property of the AppDelegate wich uses FMDB to manipulate the data in the DataBase.

我需要使用以下方法获取以前保存在数据库中的封面:

I need to get the cover previously saved in the database using the method:

- (NSData *)getCoverForMovie:(Movie *)movie;

但是,如果没有保存封面,则返回nil。

But, if there is not a cover saved, then return nil.

所以我需要使用方法保存封面

So I need to save the cover using the method

- (BOOL)saveCover:(NSData *)cover ForMovie:(Movie *)movie;

但我不知道如何编码这种方法。需要一些帮助。

But I don't know how to code this method. Need some help with it.

推荐答案

方法基于fmdb.m示例的实现



Methods Implementations based on fmdb.m examples

- (NSData *)getCoverForMovie:(Movie *)movie
{
    NSData *cover = nil;

    FMDatabase *db = [FMDatabase databaseWithPath:databasePath];

    [db open];
    FMResultSet *results = [db executeQueryWithFormat:@"SELECT * FROM COVERS WHERE movie = %i", movie.movieID];

    if([results next])
    {
        cover = [results dataForColumn:@"cover"];
    }

    return cover;
}


- (BOOL)saveCover:(NSData *)cover ForMovie:(Movie *)movie
{
    BOOL result;

    FMDatabase *db = [FMDatabase databaseWithPath:databasePath];

    [db open];

    result = [db executeUpdate:@"INSERT OR REPLACE INTO COVERS (movie, cover) VALUES (?,?)", movie.movieID, cover];

    return result;
}

感谢@ccgus的回答。

Thanks to @ccgus for his answer.

这篇关于我该如何保存&使用FMDB将图像(字节)检索到SQLite(blob)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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