OC高效率52之构建缓存时用NSCache而非NSDictionary

#import <Foundation/Foundation.h>

//Networi fetcher class
typedef void(^EOCNetworkFetcherCompletionHandler)(NSData *dara);

@interface EOCNetworkFetcher : NSObject
-(id)initWithURL:(NSURL *)url;
-(void)startWithCompletionHandler:(EOCNetworkFetcherCompletionHandler)handler;
@end


//Class that uses the network fetcher and caches results
@interface EOCClass : NSObject

@end

#import "EOCClass.h"
//NSCache胜过NSDictionary之处在于,当系统资源将要耗尽时,它可以自动删减缓存

@implementation EOCClass
{
    NSCache *_cache;
}

-(id)init{
    if (self= [super init]){
        _cache = [NSCache new];
        _cache.countLimit = 100;
        _cache.totalCostLimit = 5 *1024 *1024;
    }
    return self;
}

-(void)downloadDataFetcherURL:(NSURL *)url{
//    NSData *cachedData = [_cache objectForKey:url];
    NSPurgeableData *cachedData = [_cache objectForKey:url];//系统内存紧张时,可以把保存NSPurgeableData对象的那块内存释放掉,自动清除数据的功能
    if (cachedData){
        [cachedData beginContentAccess];
//        [self useData:cachedData];
        [cachedData endContentAccess];
    
    }else{
        EOCNetworkFetcher *fetcher = [[EOCNetworkFetcher alloc]initWithURL:url];
        [fetcher startWithCompletionHandler:^(NSData *data){
            NSPurgeableData *purgeableData = [NSPurgeableData dataWithData:data];
            [_cache setObject:purgeableData forKey:url cost:data.length];
//            [self useData:data];
            
            [purgeableData endContentAccess];
        }];
        
    
    }

}
@end


你可能感兴趣的:(OC高效率52之构建缓存时用NSCache而非NSDictionary)