上个项目需要使用通讯录,我在回顾自己设计的时候,发现自己少设计了cache这一环.

虽然直接用SQLite在初期体验上没什么大损失,不过可以预想通讯录增长到一定数量后势必会影响体验.

单例模式,全局缓存...

//
// SingletonCache.h
// StorageDemo
//
// Created by M on 16/1/15.
// Copyright © 2016年 Meng. All rights reserved.
// #import <Foundation/Foundation.h> @interface SingletonCache : NSObject +(SingletonCache *)sharedManager;
-(id)ReadWithKey:(NSString*)Key;
-(void)LoadWithData:(id)data WithKey:(NSString*) Key;
-(void)removeCacheWithKey:(NSString*)Key;
-(void)removeAllCache; @end
//
// SingletonCache.m
// StorageDemo
//
// Created by M on 16/1/15.
// Copyright © 2016年 Meng. All rights reserved.
// #import "SingletonCache.h" @interface SingletonCache ()<NSCacheDelegate> @property(nonatomic,strong)NSCache *cache; @end @implementation SingletonCache +(SingletonCache *)sharedManager
{
static SingletonCache *SingletonCacheInstance = nil;
static dispatch_once_t predicate; dispatch_once(&predicate, ^{
SingletonCacheInstance = [[self alloc] init]; });
return SingletonCacheInstance;
} /*
可实现 NSCacheDelegate 协议 - (void)cache:(NSCache *)cache willEvictObject:(id)obj; 在系统自动清除缓存的回调,
*/ -(id)init
{
if (self = [super init]) { _cache = [[NSCache alloc] init];
// _cache.countLimit = 50; 限制缓存中对象数量
_cache.delegate = self; } return self;
} -(id)ReadWithKey:(NSString*)Key
{
return [_cache objectForKey:Key];
} -(void)LoadWithData:(id)data WithKey:(NSString*) Key
{
[_cache setObject:data forKey:Key];
} -(void)removeCacheWithKey:(NSString*)Key
{ [_cache removeObjectForKey:Key]; } -(void)removeAllCache
{
[_cache removeAllObjects];
} - (void)cache:(NSCache *)cache willEvictObject:(id)obj
{ NSLog(@"Clean:%@",obj);
} @end
04-27 07:01