I studied the differences between NSMutableDictionary
and NSCache
.
One of them was that NSMutableDictionary
copy its keys and NSCache
just retain it as a strong reference.
In addition, I found that the reason why the key is copied from the NSMutableDictionary
is that if the key is only retained, a strange situation occurs when setting another value after changing the key value.
let mutableDic = NSMutableDictionary()
var dicKey: NSString = "key"
mutableDic.setObject("one", forKey: dicKey)
dicKey = "changedKey"
mutableDic.setObject("two", forKey: dicKey)
print(mutableDic.object(forKey: "key") ?? "") //"one"
print(mutableDic.object(forKey: "changedKey") ?? "") //"two"
But when I performed the same action using NSCache
I felt something strange. Because it worked fine even though it does not copy its keys!
let cache = NSCache<NSString, NSString>()
var cacheKey: NSString = "key"
cache.setObject("one", forKey: cacheKey)
cacheKey = "changedKey"
cache.setObject("two", forKey: cacheKey)
print(cache.object(forKey: "key") ?? "") //"one"
print(cache.object(forKey: "changedKey") ?? "") //"two"
So I wonder, after all what the different results will be from copying and retaining.
Is there any advantage to retain keys rather than copy except no need to implement the NScopying protocol as a key? or vice versa?
Can you explain with examples?