1.Realm
2.GYDataCenter
3.CoreData
4.FMDB
每个都有优劣之分,但是现在比较火的应用是Realm .
FMDB:
将数据缓存进数据库:
注意:任何对象都要实现NSCodeing协议才能实现转为NSData
(一般已经实现,但是自定义的类需实现其相应的方法)
1>工具类
2>导入工具类#import"FMDB.h"
3>静态
4>initialize打开数据库
+ (void)initialize
{
//1.打开数据库
NSString*path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)lastObject]stringByAppendingPathComponent:@"statuses.sqlite"];
_db= [FMDatabasedatabaseWithPath:path];
[_dbopen];
//2.创表
[_dbexecuteUpdate:@"CREATE TABLE IF NOT EXISTS t_status
(id integer PRIMARY KEY, status blob NOT NULL, idstr text NOT NULL);"];
}
/*
*数据库中存入数据
*/
+ (void)saveStatuses:(NSArray*)statuses
{
//要将一个对象存进数据库的blob字段,最好先转为NSData
//一个对象要遵守NSCoding协议,实现协议中相应的方法,才能转成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
{
//根据请求参数生成对应的查询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;";
}
//执行SQL遍历最后的结果
FMResultSet*set = [_dbexecuteQuery:sql];
NSMutableArray*statuses = [NSMutableArrayarray];
while(set.next) {
NSData*statusData = [setobjectForColumnName:@"status"];
NSDictionary*status = [NSKeyedUnarchiverunarchiveObjectWithData:statusData];
[statusesaddObject:status];
}
returnstatuses;
}
NSCoding实现方法
.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];
}
未完.....