본문 바로가기

iOS/STUDY

[iOS] NSCache

https://developer.apple.com/documentation/foundation/nscache

 

Apple Developer Documentation

 

developer.apple.com

 

NSCache

A mutable collection you user to temporarily store transient key-value pairs that are subject to eviction when resources are low.

리소스가 부족할 때 제거될 수 있는 임시 key-value 쌍을 저장하는 데 사용하는 변경 가능한 컬렉션입니다.

 = 임시 캐시 공간..!

 

class NSCache<KeyType, ObjectType> : NSObject
where KeyType : AnyObject, ObjectType : AnyObject

key 타입과 Object 타입이 AnyObject 인 것을 보면 클래스로 선언해야한다는 것을 알 수 있습니다.

 

다른 변경 가능한 컬렉션과 다른점은?

  • NSCache가 메모리를 사용하는 만큼, 너무 많이 사용하지 않게 다양한 자동 제거 정책을 통합합니다. (가지고 있다는 뜻이겠죠..!)
  • NSCache를 직접 lock 하지 않아도 다른 스레드에서 캐시 아이템을 추가, 제거, 쿼리할 수 있습니다.

https://github.com/apple/swift-corelibs-foundation/blob/main/Sources/Foundation/NSCache.swift

 

GitHub - apple/swift-corelibs-foundation: The Foundation Project, providing core utilities, internationalization, and OS indepen

The Foundation Project, providing core utilities, internationalization, and OS independence - GitHub - apple/swift-corelibs-foundation: The Foundation Project, providing core utilities, internation...

github.com

apple이 NSCache를 thread-safe하게 구성하기위해 NSLock을 자체적으로 NSCache에서 사용하는 것으로 보입니다!

 

이 말에 대해서 이해가 잘 되는 블로그 글 : https://inuplace.tistory.com/1050

결론만 적어보면 NSDictionary는 객체가 복사될 수 있다는 NSCopying 프로토콜을 채택한 객체가 Key여야하기 때문에

이 프로토콜을 채택한 객체만 사용할 수 있지만,

NSCache는 이를 채택하지 않아도 Key로 활용될 수 있기 때문이라는 의견입니다.

 

 

Topics

Managing the Name 이름 관리

/// Managing the Name

var name: String

 

Managing Cache Size 캐시 사이즈 관리

var countLimit: Int

var totalCostLimit: Int

countLimit

캐시가 보유할 수 있는 최대 object 수

기본값이 0이고, 제한이 없기 때문에 가능한 모든 object를 저장합니다.

 

totalCostLimit

object 제거를 시작하기 전에 캐시가 보유할 수 있는 최대 총 비용입니다.

기본값이 0이고, 제한이 없습니다.

object를 캐시에 추가하여 캐시의 비용이 초과되면 object가 자동으로 제거되고 이 순서는 보장되지 않습니다.

 

countLimit은 갯수관리, totalCostLimit은 최대 총 비용이기 때문에 앱마다 어떻게 캐시를 관리해야할지
다루는 이미지나 객체의 비용을 보고 결정해야할 것 같습니다.

 

Managing Discardable Content

var evictsObjectsWithDiscardedContent: Bool

protocol NSDiscardableContent

evictsObjectsWithDiscardedContent

컨텐츠가 삭제된 삭제 가능한 컨텐츠 object를 캐시에서 자동으로 제거할지 여부입니다.

기본값은 true 입니다.

 

NSDiscardableContent

https://developer.apple.com/documentation/foundation/nsdiscardablecontent

 

Managing the Delegate

var delegate: NSCacheDelegate?

protocol NSCacheDelegate

	// object가 캐시에서 제거되거나 제거되려고 할 때 호출됩니다.
    func cache(NSCache<AnyObject, AnyObject>, willEvictObject: Any)

 

 

Getting a Cached Value

// 주어진 키와 관련된 값을 반환합니다.
func object(forKey key: KeyType) -> ObjectType?

 

Adding and Removing Cached Values

// 캐시에서 지정된 키의 값을 설정합니다.
func setObject(ObjectType, forKey: KeyType)

// 캐시에서 지정된 키의 값을 설정하고 키-값 쌍을 지정된 비용과 연결합니다.
func setObject(ObjectType, forKey: KeyType, cost: Int)

// 캐시에서 지정된 키의 값을 제거합니다.
func removeObject(forKey: KeyType)

// 캐시를 비웁니다.
func removeAllObjects()