[iOS] NSURLCache && NSCachedURLResponse

NSURLCache

1. 初始化相關的幾個方法:sharedURLCache;setSharedURLCache;initWithMemoryCapacity

sharedURLCache方法返回一個NSURLCache實例。

默認情況下,內存是4M,4* 1024 * 1024;Disk爲20M,20 * 1024 * 1024;路徑在(NSHomeDirectory)/Library/Caches/(current application name, [[NSProcessInfo processInfo] processName])

setSharedURLCache可以通過這個方法來改變默認的NSURLCache。通過initWithMemoryCapacity來定製自己的NSURLCache。

 

2. cache使用相關的幾個方法:cachedResponseForRequeststoreCachedResponseremoveCachedResponseForRequest

removeAllCachedResponses

- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request;

如果對應的NSURLRequest沒有cached的response那麼返回nil

- (void)storeCachedResponse:(NSCachedURLResponse *)cachedResponse forRequest:(NSURLRequest *)request;

爲特定的NSURLRequest做cache

- (void)removeCachedResponseForRequest:(NSURLRequest *)request;

移除特定NSURLRequest的cache

- (void)removeAllCachedResponses;

移除所有的cache

 

3. property方法

- (NSUInteger)memoryCapacity;

- (NSUInteger)diskCapacity;

- (void)setMemoryCapacity:(NSUInteger)memoryCapacity;

可能會導致內存中的內存被截斷

- (void)setDiskCapacity:(NSUInteger)diskCapacity;

- (NSUInteger)currentMemoryUsage;

- (NSUInteger)currentDiskUsage;


4. Misc

a. NSURLCache在每個UIWebView的的NSURLRequest請求中都會被調用。

b. iOS設備上NSURLCache默認只能進行內存緩存。可以通過子類化NSURLCache來實現自定義的版本從而實現在DISK上緩存內容。

c. 需要重寫cachedResponseForRequest,這個會在請求發送前會被調用,從中我們可以判定是否針對此NSURLRequest返回本地數據。

d. 如果本地沒有緩存就調用下面這條語句:return [super cachedResponseForRequest:request];

 

NSCachedURLResponse

包裝了一下系統緩存機制的對象,保持了緩存對象的個性和特性。

1. NSURLCacheStoragePolicy 緩存策略有三種

enum
{
    NSURLCacheStorageAllowed,
    NSURLCacheStorageAllowedInMemoryOnly,
    NSURLCacheStorageNotAllowed,
};

默認是第一種。不過在iOS的上官方文檔上有這麼一個解釋:

Important: iOS ignores this cache policy, and instead treats it asNSURLCacheStorageAllowedInMemoryOnly.

 也就是說iOS上只有內存緩存,沒有磁盤緩存。

 

2. 構造方法

- (id)initWithResponse:(NSURLResponse *)response data:(NSData *)data;

- (id)initWithResponse:(NSURLResponse *)response data:(NSData *)data userInfo:(NSDictionary *)userInfo storagePolicy:(NSURLCacheStoragePolicy)storagePolicy;

 

3. Open API

- (NSURLResponse *)response;

- (NSData *)data;

- (NSDictionary *)userInfo;

- (NSURLCacheStoragePolicy)storagePolicy;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章