How to use NSCache in Swift
NSCache is a mutable dictionary that you could use to cache some data that are expensive to create, so it could improve your app performance.
If memory is needed by other applications, it would remove some items from the cache, minimizing its memory footprint, then some values need to be recomputed again.
One thing needs to be noticed is that key of NSCache has one KeyType : AnyObject constraint, which is different from Dictionary's Key : Hashable, so you could not use value types as a key of NSCache. For example, you have to use NSString intead of String as a key.
Here is the sample code for your reference:
class Task {
let taskID: String
let name: String
init(_ taskID: String, _ name: String) {
self.taskID = taskID
self.name = name
}
}
class TaskRepository {
let taskKey = "taskKey" as NSString
let cache = NSCache<NSString, Task>()
func getTask() -> Task {
if let cachedTask = cache.object(forKey: taskKey) {
return cachedTask
} else {
let task = Task("1", "finish the blog post")
cache.setObject(task, forKey: taskKey)
return task
}
}
}
Here are some other posts regarding iOS and Swift:
- How to scroll UITableView to the top
- How to implement recursiveDescription method in Swift
- How to implement Stack in Swift
Hope this helps,
Michael