iOS 공부와 프로젝트를 간단하게 해봤다면 Cache 방법에 대해 한번쯤 생각해 보게 됩니다.
주로 많이 듣는것은 NSCache를 듣게 되고 실제로 사용은 서드파티로 Kingfisher 같은 것을 사용해서 대신 이미지 캐싱을 하게 됩니다.
오늘은 앞에 언급한 두 가지 내용말고 URLCache에 대해 공식문서를 읽은 것에 대해 알아보고 정리해 보고자 합니다.
An Object that maps URL requests to cached response objects.
URL requests를 캐시된 response Objects에 매핑하는 객체입니다.
class URLCache: NSObject
URLCache 클래스는 URL load requests에 대한 response Caching을 NSURLRequest객체를 CachedURLResponse 객체에 매핑함으로서 구현합니다.
또한 이러한 구은 Composite in-memory와 on-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에서 온디스크 캐싱은 시스템의 디스크 공간이 부족할 때 그리고 앱이 실행되지 않는 상황에서만 제거를 합니다.iOS 8, macOS 10.10 이후 버전에서 URLCache는 Thread Safe합니다.
Thread Safe 하다는 의미는, 스레드 안전은 멀티 스레드 프로그래밍에서 일반적으로 어떤 함수나 변수, 혹은 객체가 여러 스레드로부터 동시에 접근이 이루어져도 프로그램의 실행에 문제가 없음을 뜻한다.
출처: 위키
URLCache의 instance methods가 많은 execution context로 부터 안전하게 호출 될 수 있지만 cachedResponse(for:) 나 storeCachedResponse(_:for:)과 같은 메소드에는 동일한 요청에 대한 response를 읽기/쓰기를 할 때 unavoidable race condition가 존재 합니다.
URLCache의 Subclass는 이러한 Thread Safe 방식으로 재 정의된 메소드를 구현해야 합니다.
URLCache 클래스는 현재 구현 사항되로 사용 할 수 있도록 되어있으나 특정한 요구사항이 있을 때, Subclassing 할 수 있습니다.
예를들어, 캐싱된 response를 screen하거나 또는 보안같은 여러 이유로 cache를 저장하는 mechanism에 대해 다시 구현 할 수 있게 됩니다.
이 클래스에 대한 method를 재 정의 할 경우, task parameter가 그렇지 않은 method보다 더 선호 됩니다.
task parameter가 포함된method>task parameter가 포함되지 않은method
Subclassing 할 때 task based method를 다음과 같이 작성해야합니다.
class var shared: URLCache
URLCacheClass에 대한Instance
init(memoryCapacity: Int, diskCapacity: Int, directory: URL?)
URLCache 객체를 초기화 하는 코드. memory, disk 에 대한 capacities를 정의해서 넣어줍니다.
diskPath를 정의하던 코드는 Deprecated 되었습니다func cachedResponse(for: URLRequest) -> CachedURLResponse?
func storeCachedResponse(CachedURLResponse, for: URLRequest)
func getCachedResponse(for: URLSessionDataTask, completionHandler: (CachedURLResponse?) -> Void)
func storeCachedResponse(CachedURLResponse, for: URLSessionDataTask)
func removeCachedResponse(for: URLRequest)
func removeCachedResponse(for: URLSessionDataTask)
func removeCachedResponses(since: Date)
func removeAllCachedResponses()
var currentDiskUsage: Int
var diskCapacity: Int
var currentMemoryUsage: Int
var memoryCapacity: Int
enum URLCache.StoragePolicy