OC高効率52のキャッシュの構築にNSDictionaryではなくNSCacheを用いる

1461 ワード

#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