How to use NSCache

后端 未结 5 1922
Happy的楠姐
Happy的楠姐 2020-11-27 10:25

Can someone give an example on how to use NSCache to cache a string? Or anyone has a link to a good explanation? I can\'t seem to find any..

5条回答
  •  渐次进展
    2020-11-27 10:57

    Sample code for caching a string using NSCache in Swift:

    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"
    

提交回复
热议问题