iOS緩存策略
一、思維腦圖
思維腦圖
二、緩存思想
- 數據庫底層基于Sqlite。
每個數據庫表只有Key, Value兩個字段。
直接將JSON數據存儲到Value中,并設置Key。
- 通過Key查找對應Value數據,來進行數據增刪改查操作,并更新視圖。
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;