利用fmdb做了一个简单的本地数据存储,存储对象是字典,首先通过第三方cocospod集成 fmdb (

pod 'FMDB'

)

创建一个新的类继承NSObject,代码如下:

 

.h

#import <Foundation/Foundation.h> 

@interface YMStatusCacheTool : NSObject

/** 存 */

+ (void)ym_saveWithStatus:(NSDictionary *)dataSoucre withParam:(NSString *)house_id;

//取数据

+ (NSDictionary *)ym_statuseWithParam:(NSString *)house_id;

//删

+ (void)ym_deleteWithParam:(NSString *)house_id;

@end

 

.m

 #import "YMStatusCacheTool.h"

#import <FMDB.h>

@implementation YMStatusCacheTool 

static FMDatabase * _db;

 

+ (void)initialize

{

    NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];

    

    //拼接文件名

    NSString *filePath = [cachePath stringByAppendingString:@"status.sqlite"];

    //创建了一个数据库实例

    _db = [FMDatabase databaseWithPath:filePath];

    

    //打开数据库

    if ([_db open]) {

        NSLog(@"打开成功");

    } else {

        NSLog(@"打开失败");

    }

    

    //创建表格

    BOOL flag = [_db executeUpdate:@"create table if not exists t_status (id integer primary key autoincrement,house_id integer,dict,blob);"];

    

    if (flag) {

        NSLog(@"success to creating db table");

    } else {

        NSLog(@"error when creating db table");

    }

}

 

/** 插入数据 */

+ (void)ym_saveWithStatus:(NSDictionary *)dataSoucre withParam:(NSString *)house_id

{

    //打开数据库

    if ([_db open]) {

        //转为二进制数据

        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dataSoucre];

        BOOL flag = [_db executeUpdate:@"insert into t_status (house_id,dict) values(?,?)",house_id,data];

        if (flag) {

            NSLog(@"插入成功");

        } else {

            NSLog(@"插入失败");

        }

        [_db close];

    } else {

        NSLog(@"打开失败");

    }

    

}

 

//取数据

+ (NSDictionary *)ym_statuseWithParam:(NSString *)house_id

{

    //打开数据库

    NSDictionary *dict = [NSDictionary new];

    if ([_db open]) {

        //查询语句

        NSString *sql = [NSString stringWithFormat:@"select * from t_status where house_id = '%@';",house_id];

        FMResultSet *set = [_db executeQuery:sql];

        

        while ([set next]) {

            NSData *data = [set dataForColumn:@"dict"];

            dict = [NSKeyedUnarchiver unarchiveObjectWithData:data];

        }

        [_db close];

    } else {

        NSLog(@"打开失败");

    }

    

    return dict;

}

 

//删

+ (void)ym_deleteWithParam:(NSString *)house_id

{

    //打开数据库

    if ([_db open]) {

        //删除语句

        NSString *sql = [NSString stringWithFormat:@"delete from t_status where house_id = '%@';",house_id];

        BOOL res = [_db executeUpdate:sql];

        if (!res) {

            NSLog(@"删除失败");

        } else {

            NSLog(@"删除成功");

        }

        [_db close];

    } else {

        NSLog(@"打开失败");

    }

}

 

@end

 

这个demo没有很好的封装,也没有用上异步线程,缺陷还是蛮大的,当然对于新手也挺合适。