前言:现在的项目中 推送消息需要用到 数据库缓存从服务器推送过来的消息,demo代码如下:
//
// MessageTool.m
// testdataBase
//
// Created by tinghou on 16/7/28.
// Copyright © 2016年 tinghou. All rights reserved.
//
#import "MessageTool.h"
#import "FMDB.h"
@implementation MessageTool
static FMDatabase *_db;
+ (void)initialize
{
// NSCachesDirectory NSDocumentDirectory
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"messages.sqlite"];
_db = [FMDatabase databaseWithPath:path];
[_db open];
DLog(@"path = %@",path);
// [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_message (id integer PRIMARY KEY, message blob NOT NULL);"];
[_db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_message (id integer PRIMARY KEY, message blob NOT NULL);"];
}
+ (NSMutableArray *)messagesWithParams:(NSDictionary *)params
{
NSString *sql = nil;
sql = @"SELECT * FROM t_message;";
FMResultSet *set = [_db executeQuery:sql];
NSMutableArray *messages = [NSMutableArray array];
while (set.next) {
int ID = [set intForColumn:@"id"];
DLog(@"ID = %d",ID);
NSData *Data = [set objectForColumnName:@"message"];
// NSString *isRead = [set objectForColumnName:@"isRead"];
// NSString *isRead = [NSKeyedUnarchiver unarchiveObjectWithData:isReadData];
NSDictionary *messageDic = [NSKeyedUnarchiver unarchiveObjectWithData:Data];
// NSDictionary *dic = @{@"messageDic":messageDic,
// @"isRead":isRead
// };
[messages addObject:messageDic];
}
return messages;
}
//删除
+(void)delete
{
if ([_db open]) {
NSString *deleteSql = [NSString stringWithFormat:
@"DELETE FROM t_message;"];
BOOL res = [_db executeUpdate:deleteSql];
if (!res) {
NSLog(@"error when delete db table");
} else {
NSLog(@"success to delete db table");
}
// [_db close];
}
}
+ (void)resaveMessages:(NSMutableArray *)messages{
for (NSDictionary *message in messages) {
NSData *messageData = [NSKeyedArchiver archivedDataWithRootObject:message];
[_db executeUpdateWithFormat:@"INSERT INTO t_message(message) VALUES ( %@);", messageData];
}
}
+ (void)saveMessages:(NSMutableArray *)messages
{
for (NSDictionary *message in messages) {
// NSString *isRead = @"0";
NSData *messageData = [NSKeyedArchiver archivedDataWithRootObject:message];
[_db executeUpdateWithFormat:@"INSERT INTO t_message(message) VALUES ( %@);", messageData];
}
}
@end