In my iOS app, I'm saving specific data (Realm DB containing cached models) on disk, in the cache directory of the device. The cache data increases when the user uses the app, so I would like to clear old cache data regularly.
The problem is that I don't know how to check if the models I'm deleting are used by the current view. (By trying to delete all models, I got an error telling that some model objects used by the current view were invalidated.)
To ensure that the cached models I'm deleting are not currently used, I'm currently cleaning the cache when the app terminates:
- (void)applicationWillTerminate:(UIApplication *)application {
[[ModelManager sharedInstance] deleteUnusedCacheModels];
}
Sample code in deleteUnusedCacheModels:
NSDate* limitDate = [NSDate dateWithTimeIntervalSinceNow:-(60.0 * 60.0 * 24.0 * 7.0)];
RLMResults* modelProductListArray = [ModelProductList objectsInRealm:_cacheDb
where:@"modelUpdate < %@ || modelDelete = %@", limitDate, @YES];
[_cacheDb deleteObjects:modelProductListArray];
But this code won't be executed if the user doesn't often terminate the app. (Most user leaves apps in background.)
Is there a better way for cleaning cached model data?
Thanks.
I ended up with the following solution.
Implementations in the models:
Strategy for recycling cached model on a server request:
Delete cache at the following times:
With code like this:
NSDate* limitDate = [NSDate dateWithTimeIntervalSinceNow:-(60.0 * 60.0 * 24.0 * 7.0)];
RLMResults* modelProductListArray = [ModelProductList objectsInRealm:_cacheDb
where:@"modelUpdate < %@ || modelDelete = YES", limitDate];
[_cacheDb deleteObjects:modelProductListArray];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.