programing tip

NSCache를 사용하는 방법

itbloger 2020. 7. 14. 20:54
반응형

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"

To create a single app-wide instance of NSCache (a singleton), you can easily extend NSCache to add a sharedInstance property. Just put the following code in a file called something like NSCache+Singleton.swift:

import Foundation

extension NSCache {
    class var sharedInstance : NSCache {
        struct Static {
            static let instance : NSCache = NSCache()
        }
        return Static.instance
    }
}

You can then use the cache anywhere in the app:

NSCache.sharedInstance.setObject("String for key 2", forKey: "Key2")
var result2 = NSCache.sharedInstance.objectForKey("Key2") as String
println(result2) // Prints "String for key 2"

sample Project Add CacheController.h and .m file from the sample project to your project. In class where you want to cache data , put the below code.

[[CacheController storeInstance] setCache:@"object" forKey:@"objectforkey" ];

you can set any object using this

[[CacheController storeInstance] getCacheForKey:@"objectforkey" ];

to retrive

Important: The NSCache class incorporates various auto-removal policies. if you want cache the data for permanent or you want to remove cached data in a specific time see this answer.


Shouldn't the cached objects implement the NSDiscardableContent protocol?

From the NSCache class reference: A common data type stored in NSCache objects is an object that implements the NSDiscardableContent protocol. Storing this type of object in a cache has benefits, because its content can be discarded when it is not needed anymore, thus saving memory. By default, NSDiscardableContent objects in the cache are automatically removed from the cache if their content is discarded, although this automatic removal policy can be changed. If an NSDiscardableContent object is put into the cache, the cache calls discardContentIfPossible on it upon its removal.

참고URL : https://stackoverflow.com/questions/5755902/how-to-use-nscache

반응형