iOS數(shù)據(jù)緩存(1)FMDB

1.Realm

2.GYDataCenter

3.CoreData

4.FMDB

每個都有優(yōu)劣之分,但是現(xiàn)在比較火的應(yīng)用是Realm .


FMDB:

將數(shù)據(jù)緩存進(jìn)數(shù)據(jù)庫:

注意:任何對象都要實(shí)現(xiàn)NSCodeing協(xié)議才能實(shí)現(xiàn)轉(zhuǎn)為NSData

(一般已經(jīng)實(shí)現(xiàn),但是自定義的類需實(shí)現(xiàn)其相應(yīng)的方法)

1>工具類

2>導(dǎo)入工具類#import"FMDB.h"

3>靜態(tài)

4>initialize打開數(shù)據(jù)庫

+ (void)initialize

{

//1.打開數(shù)據(jù)庫

NSString*path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)lastObject]stringByAppendingPathComponent:@"statuses.sqlite"];

_db= [FMDatabasedatabaseWithPath:path];

[_dbopen];

//2.創(chuàng)表

[_dbexecuteUpdate:@"CREATE TABLE IF NOT EXISTS t_status

(id integer PRIMARY KEY, status blob NOT NULL, idstr text NOT NULL);"];

}

/*

*數(shù)據(jù)庫中存入數(shù)據(jù)

*/

+ (void)saveStatuses:(NSArray*)statuses

{

//要將一個對象存進(jìn)數(shù)據(jù)庫的blob字段,最好先轉(zhuǎn)為NSData

//一個對象要遵守NSCoding協(xié)議,實(shí)現(xiàn)協(xié)議中相應(yīng)的方法,才能轉(zhuǎn)成NSData

for(NSDictionary*statusinstatuses) {

//NSDictionary --> NSData

NSData*statusData = [NSKeyedArchiverarchivedDataWithRootObject:status];

[_dbexecuteUpdateWithFormat:@"INSERT

INTO t_status(status, idstr) VALUES (%@, %@);", statusData, status[@"idstr"]];

}

}

+ (NSArray*)statusesWithParams:(NSDictionary*)params

{

//根據(jù)請求參數(shù)生成對應(yīng)的查詢SQL語句

NSString*sql =nil;

if(params[@"since_id"]) {

sql = [NSStringstringWithFormat:@"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遍歷最后的結(jié)果

FMResultSet*set = [_dbexecuteQuery:sql];

NSMutableArray*statuses = [NSMutableArrayarray];

while(set.next) {

NSData*statusData = [setobjectForColumnName:@"status"];

NSDictionary*status = [NSKeyedUnarchiverunarchiveObjectWithData:statusData];

[statusesaddObject:status];

}

returnstatuses;

}

NSCoding實(shí)現(xiàn)方法

.h文件

@interfaceHMShop :NSObject

.m文件

- (void)encodeWithCoder:(NSCoder*)encoder

{

[encoderencodeObject:self.nameforKey:@"name"];

[encoderencodeDouble:self.priceforKey:@"price"];

}

- (id)initWithCoder:(NSCoder*)decoder

{

if(self= [superinit]) {

self.name=

[decoderdecodeObjectForKey:@"name"];

self.price=

[decoderdecodeDoubleForKey:@"price"];

}

returnself;

}

/**NSLog*/

- (NSString*)description

{

return[NSStringstringWithFormat:@"%@

<-> %f",self.name,self.price];

}


未完.....

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容