The prehistory of the MemCache class is trivial. There is a project in development that most of the time is busy loading small amounts of data from the network. Basically JSON data and small images. In each controller, an NSMutableDictionary was declared in which the results of the queries were saved. But with the increase in the number of controllers, two problems arose - duplication of code and loss of caching results when popViewController was called.
Under the cut the solution to these problems.
It was decided to refactor the project as a result of which the MemCache singleton class was born and two categories, one each for NSString and NSObject.
The MemCache class was supposed to perform caching for a short time (in this project it was enough two minutes), to self-clear the memory when MemoryWarning occurs, as well as when the application goes into the background.
')
Link to the source at the end of the article, but for now I will tell you about the main stages of implementation.
In the init method we subscribe to notifications about memory warnings and activity loss.
- (id) init { self = [super init]; if (self != nil) { NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; [center addObserver:self selector:@selector(clearCache) name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; [center addObserver:self selector:@selector(clearCache) name:UIApplicationWillResignActiveNotification object:nil]; _lifeTime = 60.0f; } return self; }
Do not forget to unsubscribe from notifications in dealloc.
- (void)dealloc { NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; [center removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; [center removeObserver:self name:UIApplicationWillResignActiveNotification object:nil]; }
Since the cache can be cleared at any time by request or upon the occurrence of the events described above, when writing a new item, you need to check whether there is actually where to write. For each item, when adding, we launch a deferred call to remove it from the cache.
- (void)setValue:(id)value forKey:(NSString *)key { if (!_cache) { _cache = [[NSMutableDictionary alloc] init]; } [_cache setValue:value forKey:key]; [NSObject cancelPreviousPerformRequestsWithTarget:_cache selector:@selector(removeObjectForKey:) object:key]; [_cache performSelector:@selector(removeObjectForKey:) withObject:key afterDelay:_lifeTime]; }
For ease of use used categories. Now, to put an object in the cache, just write something like:
[jsonValue setMemCacheValueForKey:[[[connection originalRequest] URL] absoluteString]];
And you can get the object like this:
id val = [[url absoluteString] memCacheValue];
Repository link -
github.com/eltiren/MemCahce-IOSPS Compiled with ARC enabled.