[BEE] iOS 简单缓存实现
缓存技术已经发展得很成熟,但是,在单个设备上,特别是内存和CPU严格有限制的要根据需求来决定是否使用缓存。
先看代码:
#define DEFAULT_MAX_COUNT(16)@implementation BeeMemoryCache@synthesize clearWhenMemoryLow = _clearWhenMemoryLow;@synthesize maxCacheCount = _maxCacheCount;@synthesize cachedCount = _cachedCount;@synthesize cacheKeys = _cacheKeys;@synthesize cacheObjs = _cacheObjs;DEF_SINGLETON( BeeMemoryCache );- (id)init{self = [super init];if ( self ){_clearWhenMemoryLow = YES;_maxCacheCount = DEFAULT_MAX_COUNT;_cachedCount = 0;_cacheKeys = [[NSMutableArray alloc] init];_cacheObjs = [[NSMutableDictionary alloc] init];[self observeNotification:UIApplicationDidReceiveMemoryWarningNotification];}return self;}- (void)dealloc{[self unobserveAllNotifications];[_cacheObjs removeAllObjects]; [_cacheObjs release];[_cacheKeys removeAllObjects];[_cacheKeys release]; [super dealloc];}- (BOOL)hasCached:(NSString *)key{return [_cacheObjs objectForKey:key] ? YES : NO;}- (NSData *)dataForKey:(NSString *)key{NSObject * obj = [self objectForKey:key];if ( obj && [obj isKindOfClass:[NSData class]] ){return (NSData *)obj;}return nil;}- (void)saveData:(NSData *)data forKey:(NSString *)key{[self saveObject:data forKey:key];}- (NSObject *)objectForKey:(NSString *)key{return [_cacheObjs objectForKey:key];}- (void)saveObject:(NSObject *)object forKey:(NSString *)key{if ( nil == key )return;if ( nil == object )return;_cachedCount += 1;while ( _cachedCount >= _maxCacheCount ){NSString * tempKey = [_cacheKeys objectAtIndex:0];[_cacheObjs removeObjectForKey:tempKey];[_cacheKeys removeObjectAtIndex:0];_cachedCount -= 1;}[_cacheKeys addObject:key];[_cacheObjs setObject:object forKey:key];}- (void)deleteKey:(NSString *)key{if ( [_cacheObjs objectForKey:key] ){[_cacheKeys removeObjectIdenticalTo:key];[_cacheObjs removeObjectForKey:key];_cachedCount -= 1;}}- (void)deleteAll{[_cacheKeys removeAllObjects];[_cacheObjs removeAllObjects];_cachedCount = 0;}- (void)handleNotification:(NSNotification *)notification{if ( _clearWhenMemoryLow ){[self deleteAll];}}@end
说明:
1. 没有线程安全处理
2. 由于是运行内存有限的 iOS 设备中,注册了内存警告事件 UIApplicationDidReceiveMemoryWarningNotification
1. 可以个性内存缓存,以支持持久化
2. 可以实现更先进的缓存策略,如 LRU
3. 可以自动扩容
4. 总的来说,还是要依据设备特性来实现相应的代码
注:上述代码的一些方法,请参考: BeeFramework
THE END.