NSCache 사용 방법
누가 어떻게 사용하는지 예를 들어줄 수 있습니까?NSCache문자열을 캐시할 수 있습니까?아니면 누가 좋은 설명을 할 수 있는 링크를 가진 사람?하나도 못 찾겠어요
당신은 그것을 당신이 사용하는 것과 같은 방법으로 사용합니다.NSMutableDictionary다른 점은 다음과 같은 경우입니다.NSCache과도한 메모리 압력(즉, 너무 많은 값을 캐시하고 있음)을 감지하여 공간을 확보하기 위해 이러한 값 중 일부를 해제합니다.
런타임에 (인터넷에서 다운로드하거나, 계산을 수행하거나, 무엇이든) 이러한 값을 재생성할 수 있다면,NSCache당신의 요구에 맞을지도 모릅니다.데이터를 재생성할 수 없는 경우(예: 사용자 입력, 시간에 민감한 데이터 등)에는 데이터를 저장하지 마십시오.NSCache왜냐하면 그곳은 파괴될 것이기 때문입니다.
예: 나사산 안전을 고려하지 않음:
// Your cache should have a lifetime beyond the method or handful of methods
// that use it. For example, you could make it a field of your application
// delegate, or of your view controller, or something like that. Up to you.
NSCache *myCache = ...;
NSAssert(myCache != nil, @"cache object is missing");
// Try to get the existing object out of the cache, if it's there.
Widget *myWidget = [myCache objectForKey: @"Important Widget"];
if (!myWidget) {
// It's not in the cache yet, or has been removed. We have to
// create it. Presumably, creation is an expensive operation,
// which is why we cache the results. If creation is cheap, we
// probably don't need to bother caching it. That's a design
// decision you'll have to make yourself.
myWidget = [[[Widget alloc] initExpensively] autorelease];
// Put it in the cache. It will stay there as long as the OS
// has room for it. It may be removed at any time, however,
// at which point we'll have to create it again on next use.
[myCache setObject: myWidget forKey: @"Important Widget"];
}
// myWidget should exist now either way. Use it here.
if (myWidget) {
[myWidget runOrWhatever];
}
@implementation ViewController
{
NSCache *imagesCache;
}
- (void)viewDidLoad
{
imagesCache = [[NSCache alloc] init];
}
// How to save and retrieve NSData into NSCache
NSData *imageData = [imagesCache objectForKey:@"KEY"];
[imagesCache setObject:imageData forKey:@"KEY"];
Swift에서 NSCache를 사용하여 문자열을 캐싱하기 위한 샘플 코드:
var cache = NSCache()
cache.setObject("String for key 1", forKey: "Key1")
var result = cache.objectForKey("Key1") as String
println(result) // Prints "String for key 1"
애플리케이션 전체에 걸친 단일 NSCache 인스턴스(싱글톤)를 생성하려면 NSCache를 쉽게 확장하여 공유 인스턴스 속성을 추가할 수 있습니다.NSCache+Singleton.swift와 같은 파일에 다음 코드를 넣으면 됩니다.
import Foundation
extension NSCache {
class var sharedInstance : NSCache {
struct Static {
static let instance : NSCache = NSCache()
}
return Static.instance
}
}
그런 다음 앱의 모든 위치에서 캐시를 사용할 수 있습니다.
NSCache.sharedInstance.setObject("String for key 2", forKey: "Key2")
var result2 = NSCache.sharedInstance.objectForKey("Key2") as String
println(result2) // Prints "String for key 2"
샘플 프로젝트의 CacheController.h 및 .m 파일을 샘플 프로젝트에서 프로젝트에 추가합니다.데이터를 캐시할 클래스에 다음 코드를 입력합니다.
[[CacheController storeInstance] setCache:@"object" forKey:@"objectforkey" ];
이를 사용하여 모든 개체를 설정할 수 있습니다.
[[CacheController storeInstance] getCacheForKey:@"objectforkey" ];
검색하기 위해
중요:NSCache 클래스에는 다양한 자동 제거 정책이 통합되어 있습니다.영구적으로 데이터를 캐시하거나 특정 시간 내에 캐시된 데이터를 제거하려면 다음 답변을 참조하십시오.
캐시된 개체는 NSDiscardableContent 프로토콜을 구현해야 하지 않습니까?
NSCache 클래스 참조:NSCache 개체에 저장된 공통 데이터 유형은 NSDiscardableContent 프로토콜을 구현하는 개체입니다.이러한 유형의 개체를 캐시에 저장하면 더 이상 필요하지 않을 때 내용을 삭제할 수 있으므로 메모리를 절약할 수 있습니다.기본적으로 캐시의 NSDiscardableContent 개체는 콘텐츠가 삭제되면 자동으로 캐시에서 제거되지만 이 자동 제거 정책은 변경될 수 있습니다.NSDiscardableContent 개체가 캐시에 저장된 경우 캐시는 해당 개체를 제거할 때 해당 개체에 대해 discardContentIfPossible을 호출합니다.
언급URL : https://stackoverflow.com/questions/5755902/how-to-use-nscache
'programing' 카테고리의 다른 글
| SQL에 if-then-else 논리가 있습니까? (0) | 2023.05.04 |
|---|---|
| 그래픽으로 표시할 수 없는 Excel의 외부 데이터 쿼리에 매개 변수를 추가하는 방법은 무엇입니까? (0) | 2023.05.04 |
| 스택 패널에서 항목 정렬? (0) | 2023.05.04 |
| 각도 + 재료 - 데이터 원본을 새로 고치는 방법(매트 테이블) (0) | 2023.05.04 |
| 어떤 iOS SDK가 있는지 어떻게 확인합니까? (0) | 2023.05.04 |