面试iOS 网络编程ios开发

iOS缓存策略

2016-08-16  本文已影响1130人  LuisX
iOS缓存策略

一、思维脑图

思维脑图

思维脑图详情

二、缓存思想

1.使用SDWebImage缓存图片。
2.使用YTKKeyValueStore更方便使用FMDB。
3.使用FMDB操作数据库。

SDWebImage官方地址: https://github.com/rs/SDWebImage
YTKKeyValueStore官方地址: https://github.com/yuantiku/YTKKeyValueStore
FMDB官方地址: https://github.com/ccgus/fmdb


三、使用YTKKeyValueStore操作数据库

iOS端数据量不大,使用最简单直接的Key-Value存储就能带来开发上的效率优势。
1.Model层的代码编写简单,易于测试。
2.由于Value是JSON格式,所以在做Model字段更改时,易于扩展和兼容。

//1.打开数据库(若有),创建数据库(若无)
YTKKeyValueStore *store = [[YTKKeyValueStore alloc] initDBWithName:@"test.db"];
//2.创建数据库表(若无),忽略(若无)
NSString *tableName = @"user_table";
[store createTableWithName:tableName];
//3.写入数据
NSString *key = @"1";
NSDictionary *user = @{@"id": @1, @"name": @"tangqiao", @"age": @30};
[store putObject:user withId:key intoTable:tableName];
//4.读取数据
NSDictionary *queryUser = [store getObjectById:key fromTable:tableName];
NSLog(@"query data result: %@", queryUser);

默认创建在Document路径下。
若打开的数据库不存在则创建。

// 打开名为test.db的数据库,如果该文件不存在,则创新一个新的。
YTKKeyValueStore *store = [[YTKKeyValueStore alloc] initDBWithName:@"test.db"];

若创建的表存在则忽略。

YTKKeyValueStore *store = [[YTKKeyValueStore alloc] initDBWithName:@"test.db"];
NSString *tableName = @"user_table";
// 创建名为user_table的表,如果已存在,则忽略该操作
[store createTableWithName:tableName];

通过Key-Value来读写数据库表中数据。
Value支持类型:NSString, NSNumber, NSDictionary,NSArray。

//写入数据
- (void)putString:(NSString *)string withId:(NSString *)stringId intoTable:(NSString *)tableName;
- (void)putNumber:(NSNumber *)number withId:(NSString *)numberId intoTable:(NSString *)tableName;
- (void)putObject:(id)object withId:(NSString *)objectId intoTable:(NSString *)tableName;
//读取数据
- (NSString *)getStringById:(NSString *)stringId fromTable:(NSString *)tableName;
- (NSNumber *)getNumberById:(NSString *)numberId fromTable:(NSString *)tableName;
- (id)getObjectById:(NSString *)objectId fromTable:(NSString *)tableName;
// 清除数据表中所有数据
- (void)clearTable:(NSString *)tableName;
// 删除指定key的数据
- (void)deleteObjectById:(NSString *)objectId fromTable:(NSString *)tableName;
// 批量删除一组key数组的数据
- (void)deleteObjectsByIdArray:(NSArray *)objectIdArray fromTable:(NSString *)tableName;
// 批量删除所有带指定前缀的数据
- (void)deleteObjectsByIdPrefix:(NSString *)objectIdPrefix fromTable:(NSString *)tableName;

YTKKeyValueItem类带有createdTime字段,可以获得该条数据的插入(或更新)时间,以便上层做复杂的处理(例如用来做缓存过期逻辑)。

// 获得指定key的数据
- (YTKKeyValueItem *)getYTKKeyValueItemById:(NSString *)objectId fromTable:(NSString *)tableName;
// 获得所有数据
- (NSArray *)getAllItemsFromTable:(NSString *)tableName;

YTKKeyValueStore参考文档

上一篇 下一篇

猜你喜欢

热点阅读