iOSsqlite存储图片内容并展示

首先我们要在.h中导入头文件

#import

#import "Model.h"

当然不要忘记导入sqlite的库

然后实现一些方法

{

//给数据库创建一个指针;

sqlite3 * sqliteDB;

NSString *newpath;

}

//单例

+(instancetype)shareData;

//初始化数据库

-(void)create;

//添加数据

-(void)insert:(Model *)mo;

//查询数据

-(NSMutableArray *)select;

////关闭数据库

//-(void)open;

//关闭数据库

-(void)close;

@end

其次实在.m中实现这些方法

static LoadData * ld = nil;

@implementation LoadData

//单例

+(instancetype)shareData{

static dispatch_once_t onceToken;

dispatch_once(&onceToken, ^{

ld = [[LoadData alloc]init];

});

return ld;

}

+(instancetype)allocWithZone:(struct _NSZone *)zone{

static dispatch_once_t onceToken;

dispatch_once(&onceToken, ^{

ld = [super allocWithZone:zone];

});

return ld;

}

-(id)copy{

return self;

}

-(id)mutableCopy{

return self;

}

//初始化数据库

-(void)create{

//创建沙盒路径

NSString * path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];

//创建沙盒路径下的.db文件

newpath = [path stringByAppendingPathComponent:@"by.db"];

//打开数据库

sqlite3_open([newpath UTF8String], &sqliteDB);

//添加表格

[self inittable];

}

//创建表格

-(void)inittable{

//创建sql语句

const char * sql = "create table imgtable ( id integer primary key, image text)";

//创建预编译指针

sqlite3_stmt * stmt;

//把sql语句绑定到预编译指针中

sqlite3_prepare(sqliteDB, sql, -1, &stmt, nil);

//执行

sqlite3_step(stmt);

//释放预编译指针

sqlite3_finalize(stmt);

}

//添加数据

-(void)insert:(Model *)mo{

//    const char * sqla = "insert into aiya values(null,?)";

//创建sql语句

const char * sql = "insert into imgtable values (null,?)";

sqlite3_stmt * stmt;

sqlite3_prepare(sqliteDB, sql, -1, &stmt, nil);

sqlite3_bind_text(stmt, 1, [mo.img UTF8String], -1, nil);

//绑定问号

//    sqlite3_step(stmt);

if (sqlite3_step(stmt) == SQLITE_DONE) {

NSLog(@"成功");

}

sqlite3_finalize(stmt);

}

//查询数据

-(NSMutableArray *)select{

const char * sql = "select * from imgtable";

sqlite3_stmt * stmt;

sqlite3_prepare(sqliteDB, sql, -1, &stmt, nil);

NSMutableArray * arr = [[NSMutableArray alloc]init];

while (sqlite3_step(stmt) == SQLITE_ROW) {

Model * M = [[Model alloc]init];

M.img = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 1)];

NSData * data = [[NSData alloc]initWithBase64Encoding:M.img];

[arr addObject:data];

}

return arr;

}

//关闭数据库

-(void)close{

sqlite3_close(sqliteDB);

}

然后在viewcontroller中设置两个按钮并实现其方法

self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"name" style:UIBarButtonItemStyleDone target:self action:@selector(back)];;

-(void)back{

Model * m = [[Model alloc]init];

NSData * data = UIImageJPEGRepresentation(self.img.image, 0.5f);

m.img = [data base64Encoding];

[[LoadData shareData]insert:m];

MyViewController * my = [[MyViewController alloc]init];

[self.navigationController pushViewController:my animated:YES];

}

你可能感兴趣的:(iOSsqlite存储图片内容并展示)