iOS数据库存取复杂类型数组
2016-02-20 本文已影响1813人
大大大龙
在项目实现中经常遇到会用数据库存取图片/音频/视频等复杂类型数组,当数组count确定时,可以根据个数存取,但大部分时候数组的个数是不能确定的.
这时,我们就可以利用归档/反归档,把复杂类型转为数据库可存取的Data类型,来方便使用,下面本文以图片数组为例,简单的介绍下具体实现方法.
sqlite不支持存取复杂类型,但它为我们提供了BLOB类型,来存取Data类型.需要注意的是,如果直接把图片数组归档为Data存进sqlite,是存不进去的.我们需要先把数组中的每个图片转为Data,存入数组,再把装有所有图片Data的数组归档为Data,并以BLOB类型存入sqlite,才可以实现.
大致的思路就是这样的,下面代码跟上~~
static DataManager *dataBase = nil;
static FMDatabase *db = nil;
+(instancetype)sharedDataBase{
@synchronized(self) {
if (nil == dataBase) {
dataBase = [[DataManager alloc]init];
[dataBase openDB];
}
}
return dataBase;
}
// 打开数据库
- (void)openDB{
if (nil != db) {
return;
}
NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSLog(@"%@",documentPath);
documentPath = [documentPath stringByAppendingPathComponent:@"/student.sqlite"];
db = [FMDatabase databaseWithPath:documentPath];
if ([db open]) {
BOOL result = [db executeUpdate:@"CREATE TABLE IF NOT EXISTS Student ('ID' TEXT PRIMARY KEY NOT NULL, 'name' TEXT NOT NULL, 'age' TEXT NOT NULL, 'imgArray' BLOB);"];
if (result) {
NSLog(@"数据库打开成功!");
}else{
NSLog(@"数据库打开失败!");
}
}
}
// 往数据库插入model
- (void)insertStudentWithModel:(StudentModel *)model{
// img 转 imgData
NSMutableArray *imgDataArray = [NSMutableArray arrayWithCapacity:5];
for (UIImage *img in model.imgArray) {
NSData *imgData = UIImageJPEGRepresentation(img, 1);
[imgDataArray addObject:imgData];
}
// imgArray归档
NSMutableData * imgArrayData = [NSMutableData dataWithCapacity:500];
NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:imgArrayData];
[archiver encodeObject:imgDataArray forKey:[NSString stringWithString:model.ID]];
[archiver finishEncoding];
BOOL result = [db executeUpdate:@"INSERT INTO student (ID,name,age,imgArray) VALUES (?,?,?,?);", model.ID,model.name,model.age,imgArrayData,nil,nil];
if (result) {
NSLog(@"插入成功!");
}else{
NSLog(@"插入失败!");
}
}
// 根据ID查询笔记
- (StudentModel *)selectStudentByID:(NSString *)ID{
FMResultSet *result = [db executeQuery:@"SELECT * FROM Student where id = ?",ID];
NSMutableArray *array = [NSMutableArray arrayWithCapacity:5];
while ([result next]) {
StudentModel *model = [[StudentModel alloc]init];
model.name = [result stringForColumn:@"name"];
model.ID = [result stringForColumn:@"ID"];
model.age = [result stringForColumn:@"age"];
NSData *imgArrayData = [result dataForColumn:@"imgArray"];
// imgArray反归档
NSKeyedUnarchiver * unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:imgArrayData];
NSMutableArray *imgDataArray = [unarchiver decodeObjectForKey:model.ID];
[unarchiver finishDecoding];
// imgData 转 img
NSMutableArray *imgArray = [NSMutableArray arrayWithCapacity:5];
for (NSData *data in imgDataArray) {
UIImage *img = [UIImage imageWithData:data];
[imgArray addObject:img];
}
model.imgArray = imgArray;
[array addObject:model];
}
[result close];
if (array.count == 0) {
NSLog(@"没有查到!");
return nil;
}
return array[0];
}
我会持续更新iOS教程,喜欢就关注下啦~~~~~~~_