@@ -59,6 +59,11 @@ @interface LKDBHelper ()
59
59
@property (nonatomic , copy ) NSString *dbPath;
60
60
@property (nonatomic , strong ) NSMutableArray *createdTableNames;
61
61
@property (nonatomic , strong ) NSRecursiveLock *threadLock;
62
+
63
+ @property (nonatomic , assign ) NSInteger lastExecuteDBTime;
64
+ @property (nonatomic , assign ) BOOL runingAutoCloseTimer;
65
+ @property (nonatomic , assign ) NSInteger autoCloseDBDelayTime;
66
+
62
67
@end
63
68
64
69
@implementation LKDBHelper
@@ -162,6 +167,9 @@ - (instancetype)initWithDBPath:(NSString *)filePath
162
167
if (self) {
163
168
self.threadLock = [[NSRecursiveLock alloc ] init ];
164
169
self.createdTableNames = [NSMutableArray array ];
170
+ self.lastExecuteDBTime = [[NSDate date ] timeIntervalSince1970 ];
171
+ self.autoCloseDBDelayTime = 20 ;
172
+ [self startAutoCloseTimer ];
165
173
166
174
[self setDBPath: filePath];
167
175
[LKDBHelper dbHelperWithPath: nil save: self ];
@@ -265,14 +273,13 @@ - (void)executeDB:(void (^)(FMDatabase *db))block
265
273
return ;
266
274
}
267
275
[self .threadLock lock ];
268
-
276
+
269
277
if (self.usingdb != nil ) {
270
278
block (self.usingdb );
271
279
} else {
272
280
if (self.bindingQueue == nil ) {
273
281
self.bindingQueue = [[FMDatabaseQueue alloc ] initWithPath: self .dbPath
274
282
flags: LKDBOpenFlags];
275
- [self .createdTableNames removeAllObjects ];
276
283
[self .bindingQueue inDatabase: ^(FMDatabase *db) {
277
284
db.logsErrors = LKDBLogErrorEnable;
278
285
if (_encryptionKey.length > 0 ) {
@@ -286,10 +293,45 @@ - (void)executeDB:(void (^)(FMDatabase *db))block
286
293
self.usingdb = nil ;
287
294
}];
288
295
}
289
-
296
+
297
+ self.lastExecuteDBTime = [[NSDate date ] timeIntervalSince1970 ];
298
+
299
+ if (!self.runingAutoCloseTimer ) {
300
+ [self startAutoCloseTimer ];
301
+ }
302
+
290
303
[self .threadLock unlock ];
291
304
}
292
305
306
+ - (void )setAutoCloseDBTime : (NSInteger )time {
307
+ if (time < 10 ) {
308
+ time = 10 ;
309
+ }
310
+ self.autoCloseDBDelayTime = time;
311
+ }
312
+
313
+ - (void )startAutoCloseTimer {
314
+ self.runingAutoCloseTimer = YES ;
315
+ dispatch_after (dispatch_time (DISPATCH_TIME_NOW, (int64_t )(self.autoCloseDBDelayTime * NSEC_PER_SEC)), dispatch_get_global_queue (0 , 0 ), ^{
316
+ [self .threadLock lock ];
317
+ self.runingAutoCloseTimer = NO ;
318
+ BOOL hasClosed = [self autoCloseDBConnection ];
319
+ if (!hasClosed) {
320
+ [self startAutoCloseTimer ];
321
+ }
322
+ [self .threadLock unlock ];
323
+ });
324
+ }
325
+
326
+ - (BOOL )autoCloseDBConnection {
327
+ NSInteger now = [[NSDate date ] timeIntervalSince1970 ];
328
+ if (now - self.lastExecuteDBTime > 10 ) {
329
+ [self closeDB ];
330
+ return YES ;
331
+ }
332
+ return NO ;
333
+ }
334
+
293
335
- (BOOL )executeSQL : (NSString *)sql arguments : (NSArray *)args
294
336
{
295
337
__block BOOL execute = NO ;
0 commit comments