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..
相关问题
- CALayer - backgroundColor flipped?
- Core Data lightweight migration crashes after App
- How can I implement password recovery in an iPhone
- State preservation and restoration strategies with
- “Zero out” sensitive String data in Swift
相关文章
- 现在使用swift开发ios应用好还是swift?
- UITableView dragging distance with UIRefreshContro
- TCC __TCCAccessRequest_block_invoke
- Where does a host app handle NSExtensionContext#co
- xcode 4 garbage collection removed?
- Xcode: Is there a way to change line spacing (UI L
- Unable to process app at this time due to a genera
- Swift - hide pickerView after value selected
Sample code for caching a string using NSCache in Swift:
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:
You can then use the cache anywhere in the app:
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.
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.
you can set any object using this
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.
You use it the same way you would use
NSMutableDictionary
. The difference is that whenNSCache
detects excessive memory pressure (i.e. it's caching too many values) it will release some of those values to make room.If you can recreate those values at runtime (by downloading from the Internet, by doing calculations, whatever) then
NSCache
may suit your needs. If the data cannot be recreated (e.g. it's user input, it is time-sensitive, etc.) then you should not store it in anNSCache
because it will be destroyed there.Example, not taking thread safety into account: