这是个很简单的库,我花了1个小时不到的时间看完了不到400行的源代码和一些issue。
详细用法看作者的这篇介绍:https://github.com/yuantiku/YTKKeyValueStore。作为持久化的一个方案,却很实用。很常见的一个需求是缓存每次网络请求的内容,用key value的方式再合适不过了。
其中有两个疑问
1)库里使用NSJSONSerialization的方式存储数据,磁盘容量使用比较大,作者也没改过来。这个issue里有讨论。https://github.com/yuantiku/YTKKeyValueStore/issues/24
2)每个操作方法都带有tablename,使用不便,我提了一个issue给作者,实际上,我也在YTKKeyValueStore做了一下简单的封装,将tablename作为实例变量。可以看这个issue:https://github.com/yuantiku/YTKKeyValueStore/issues/34
原理介绍
能持久化的对象必须是[NSJSONSerializationdataWithJSONObject]能转化的对象,自定义对象可以通过类似YYModel的库,转换为NSDictionary。所以这个不是问题。
然后将对象转化为字符串,保存在sqlite数据库中。
- (void)putObject:(id)object withId:(NSString*)objectId intoTable:(NSString*)tableName {
if([YTKKeyValueStorecheckTableName:tableName] ==NO) {
return;
}
NSError* error;
NSData* data = [NSJSONSerializationdataWithJSONObject:objectoptions:0error:&error];
if(error) {
debugLog(@"ERROR, faild to get json data");
return;
}
NSString* jsonString = [[NSStringalloc]initWithData:dataencoding:(NSUTF8StringEncoding)];
NSDate* createdTime = [NSDatedate];
NSString* sql = [NSStringstringWithFormat:UPDATE_ITEM_SQL, tableName];
__blockBOOLresult;
[_dbQueueinDatabase:^(FMDatabase*db) {
result = [dbexecuteUpdate:sql, objectId, jsonString, createdTime];
}];
if(!result) {
debugLog(@"ERROR, failed to insert/replace into table: %@", tableName);
}
}
- (id)getObjectById:(NSString*)objectId fromTable:(NSString*)tableName {
YTKKeyValueItem* item = [selfgetYTKKeyValueItemById:objectIdfromTable:tableName];
if(item) {
returnitem.itemObject;
}else{
returnnil;
}
}
- (YTKKeyValueItem*)getYTKKeyValueItemById:(NSString*)objectId fromTable:(NSString*)tableName {
if([YTKKeyValueStorecheckTableName:tableName] ==NO) {
returnnil;
}
NSString* sql = [NSStringstringWithFormat:QUERY_ITEM_SQL, tableName];
__blockNSString* json =nil;
__blockNSDate* createdTime =nil;
[_dbQueueinDatabase:^(FMDatabase*db) {
FMResultSet* rs = [dbexecuteQuery:sql, objectId];
if([rsnext]) {
json = [rsstringForColumn:@"json"];
createdTime = [rsdateForColumn:@"createdTime"];
}
[rsclose];
}];
if(json) {
NSError* error;
idresult = [NSJSONSerializationJSONObjectWithData:[jsondataUsingEncoding:NSUTF8StringEncoding]
options:(NSJSONReadingAllowFragments)error:&error];
if(error) {
debugLog(@"ERROR, faild to prase to json");
returnnil;
}
YTKKeyValueItem* item = [[YTKKeyValueItemalloc]init];
item.itemId= objectId;
item.itemObject= result;
item.createdTime= createdTime;
returnitem;
}else{
returnnil;
}
}
网友评论