以新浪微博加載微博的工具類為例:
@implementation HWStatusTool
static FMDatabase* _db;
+ (void)initialize
{
//1.打開(kāi)數(shù)據(jù)庫(kù)
NSString*path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) lastObject] stringByAppendingPathComponent:@"statuses.sqlite"];
_db= ?[FMDatabasedatabaseWithPath:path];//使用FMDB
[_dbopen];
//2.創(chuàng)表
[_db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_status (id integer PRIMARY KEY, status blob NOT NULL, idstr text NOT NULL);"];
}
+ (NSArray*)statusesWithParams:(NSDictionary*)params
{
//根據(jù)請(qǐng)求參數(shù)生成對(duì)應(yīng)的查詢SQL語(yǔ)句
NSString*sql =nil;
if(params[@"since_id"]) {
sql = [NSString stringWithFormat:@"SELECT * FROM t_status WHERE idstr > %@ ORDER
BY idstr DESC LIMIT 20;", params[@"since_id"]];
}elseif(params[@"max_id"]) {
sql = [NSStringstringWithFormat:@"SELECT * FROM t_status WHERE idstr <= %@ ORDER
BY idstr DESC LIMIT 20;", params[@"max_id"]];
}else{
sql =@"SELECT * FROM t_status ORDER BY idstr DESC LIMIT
20;";
}
//執(zhí)行SQL
FMResultSet*set = [_dbexecuteQuery:sql];
NSMutableArray*statuses = [NSMutableArray array];
while(set.next) {
NSData*statusData = [set objectForColumnName:@"status"];
NSDictionary*status = [NSKeyedUnarchiver unarchiveObjectWithData:statusData];//重點(diǎn)
[statuses addObject:status];
}
returnstatuses;
}
+ (void)saveStatuses:(NSArray*)statuses
{
//要將一個(gè)對(duì)象存進(jìn)數(shù)據(jù)庫(kù)的blob字段,最好先轉(zhuǎn)為NSData
//一個(gè)對(duì)象要遵守NSCoding協(xié)議,實(shí)現(xiàn)協(xié)議中相應(yīng)的方法,才能轉(zhuǎn)成NSData
for(NSDictionary*status in statuses) {
// NSDictionary --> NSData
NSData*statusData = [NSKeyedArchiver archivedDataWithRootObject:status];//重點(diǎn)
[_db executeUpdateWithFormat:@"INSERT INTO t_status(status, idstr) VALUES (%@,
%@);", statusData, status[@"idstr"]];
}
}
@end