From 81a94377d231a405a35147b529b100b00082b6d2 Mon Sep 17 00:00:00 2001 From: jiangzhichao Date: Wed, 24 Aug 2016 16:06:40 +0800 Subject: [PATCH] Support Transaction --- YTKKeyValueStore/YTKKeyValueStore.h | 2 ++ YTKKeyValueStore/YTKKeyValueStore.m | 32 +++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/YTKKeyValueStore/YTKKeyValueStore.h b/YTKKeyValueStore/YTKKeyValueStore.h index 2dff8f5..27ea7aa 100644 --- a/YTKKeyValueStore/YTKKeyValueStore.h +++ b/YTKKeyValueStore/YTKKeyValueStore.h @@ -37,6 +37,8 @@ - (void)putObject:(id)object withId:(NSString *)objectId intoTable:(NSString *)tableName; +- (void)putObjects:(NSArray *)keyValueItems intoTable:(NSString *)tableName; + - (id)getObjectById:(NSString *)objectId fromTable:(NSString *)tableName; - (YTKKeyValueItem *)getYTKKeyValueItemById:(NSString *)objectId fromTable:(NSString *)tableName; diff --git a/YTKKeyValueStore/YTKKeyValueStore.m b/YTKKeyValueStore/YTKKeyValueStore.m index ef3ee45..bbeb217 100644 --- a/YTKKeyValueStore/YTKKeyValueStore.m +++ b/YTKKeyValueStore/YTKKeyValueStore.m @@ -182,6 +182,38 @@ - (void)putObject:(id)object withId:(NSString *)objectId intoTable:(NSString *)t } } +- (void)putObjects:(NSArray *)keyValueItems intoTable:(NSString *)tableName +{ + if ([YTKKeyValueStore checkTableName:tableName] == NO) { + return; + } + __block BOOL result; + [_dbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) { + for (YTKKeyValueItem *item in keyValueItems) { + id object = item.itemObject; + NSString *objectId = item.itemId; + + NSError * error; + NSData * data = [NSJSONSerialization dataWithJSONObject:object options:0 error:&error]; + if (error) { + debugLog(@"ERROR, faild to get json data"); + continue; + } + + NSString * jsonString = [[NSString alloc] initWithData:data encoding:(NSUTF8StringEncoding)]; + NSDate * createdTime = [NSDate date]; + NSString * sql = [NSString stringWithFormat:UPDATE_ITEM_SQL, tableName]; + + result = [db executeUpdate:sql, objectId, jsonString, createdTime]; + if (!result) { + *rollback = YES; + debugLog(@"ERROR, rollback to insert/replace into table: %@", tableName); + return; + } + } + }]; +} + - (id)getObjectById:(NSString *)objectId fromTable:(NSString *)tableName { YTKKeyValueItem * item = [self getYTKKeyValueItemById:objectId fromTable:tableName]; if (item) {