[iOS] URLCache

.onNext("Volga")·2023년 2월 6일
0

iOS

목록 보기
7/7

들어가기 전에

iOS 공부와 프로젝트를 간단하게 해봤다면 Cache 방법에 대해 한번쯤 생각해 보게 됩니다.
주로 많이 듣는것은 NSCache를 듣게 되고 실제로 사용은 서드파티로 Kingfisher 같은 것을 사용해서 대신 이미지 캐싱을 하게 됩니다.

오늘은 앞에 언급한 두 가지 내용말고 URLCache에 대해 공식문서를 읽은 것에 대해 알아보고 정리해 보고자 합니다.

URLCache

An Object that maps URL requests to cached response objects.

URL requests를 캐시된 response Objects에 매핑하는 객체입니다.

Declaration

class URLCache: NSObject

Overview

URLCache 클래스는 URL load requests에 대한 response CachingNSURLRequest객체를 CachedURLResponse 객체에 매핑함으로서 구현합니다.
또한 이러한 구은 Composite in-memoryon-disk 캐싱을 제공하고 두 부분에 대한 size를 조절 할 수 있습니다.
캐시 데이터가 persistently하게 저장되는 경로 역시 control 가능합니다!

Note
In iOS, the on-disk cache may be purged when the system runs low on disk space, but only when your app is not running.

  • iOS에서 온디스크 캐싱은 시스템의 디스크 공간이 부족할 때 그리고 앱이 실행되지 않는 상황에서만 제거를 합니다.

Thread Safety

iOS 8, macOS 10.10 이후 버전에서 URLCacheThread Safe합니다.

Thread Safe 하다는 의미는, 스레드 안전은 멀티 스레드 프로그래밍에서 일반적으로 어떤 함수나 변수, 혹은 객체가 여러 스레드로부터 동시에 접근이 이루어져도 프로그램의 실행에 문제가 없음을 뜻한다.
출처: 위키

URLCacheinstance methods가 많은 execution context로 부터 안전하게 호출 될 수 있지만 cachedResponse(for:)storeCachedResponse(_:for:)과 같은 메소드에는 동일한 요청에 대한 response를 읽기/쓰기를 할 때 unavoidable race condition가 존재 합니다.

URLCacheSubclass는 이러한 Thread Safe 방식으로 재 정의된 메소드를 구현해야 합니다.

Subclassing Notes

URLCache 클래스는 현재 구현 사항되로 사용 할 수 있도록 되어있으나 특정한 요구사항이 있을 때, Subclassing 할 수 있습니다.
예를들어, 캐싱된 responsescreen하거나 또는 보안같은 여러 이유로 cache를 저장하는 mechanism에 대해 다시 구현 할 수 있게 됩니다.

이 클래스에 대한 method를 재 정의 할 경우, task parameter가 그렇지 않은 method보다 더 선호 됩니다.

task parameter포함된 method > task parameter포함되지 않은 method

Subclassing 할 때 task based method를 다음과 같이 작성해야합니다.

Topics

Getting and Setting Shared Cache

class var shared: URLCache

URLCache Class에 대한 Instance

Creating a New Cache Object

init(memoryCapacity: Int, diskCapacity: Int, directory: URL?)

URLCache 객체를 초기화 하는 코드. memory, disk 에 대한 capacities를 정의해서 넣어줍니다.

  • 기존에 쓰던 diskPath를 정의하던 코드는 Deprecated 되었습니다

Getting and Storing Cached Objects

func cachedResponse(for: URLRequest) -> CachedURLResponse?
  • Returns the cached URL response in the cache for the specified URL request.
func storeCachedResponse(CachedURLResponse, for: URLRequest)
  • Stores a cached URL response for a specified request.
func getCachedResponse(for: URLSessionDataTask, completionHandler: (CachedURLResponse?) -> Void)
  • Gets the cached URL response for a data task, passing it to the provided completion handler.
func storeCachedResponse(CachedURLResponse, for: URLSessionDataTask)
  • Stores a cached URL response for a specified data task.

Removing Cached Objects

func removeCachedResponse(for: URLRequest)
  • Removes the cached URL response for a specified URL request.
func removeCachedResponse(for: URLSessionDataTask)
  • Removes the cached URL response for a specified data task.
func removeCachedResponses(since: Date)
  • Clears the given cache of any cached responses since the provided date.
func removeAllCachedResponses()
  • Clears the receiver’s cache, removing all stored cached URL responses.

Getting and Setting On-disk Cache Properties

var currentDiskUsage: Int
  • The current size of the on-disk cache, in bytes.
var diskCapacity: Int
  • The capacity of the on-disk cache, in bytes.

Getting and Setting In-memory Cache Properties

var currentMemoryUsage: Int
  • The current size of the in-memory cache, in bytes.
var memoryCapacity: Int
  • The capacity of the in-memory cache, in bytes.

Cache Storage Policies

enum URLCache.StoragePolicy
  • These constants specify the caching strategy used by an CachedURLResponse object.
profile
iOS 개발자 volga입니다~

0개의 댓글