#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