3

If I'm not wrong, there is no way to know the number of the objects stored in an NSCache, but is there any way to just know if the cache is empty or it already contains any object?

AppsDev
  • 12,319
  • 23
  • 93
  • 186
  • 1
    Could you please tell us the use case? – Sulthan May 07 '17 at 15:49
  • 1
    @Sulthan Its for testing purposes, to log the status of the cache at certain moments (simply knowing if the cache is empty or not would be enough for me) – AppsDev May 07 '17 at 16:22
  • Can't you just check if a specified key is cached? Can't you mock `NSCache`? – Sulthan May 07 '17 at 16:38
  • 1
    @Sulthan No, at certain points I dont know about the possible keys in the cache, and actually I don't care about an specific key-object pair – AppsDev May 07 '17 at 16:47

1 Answers1

1

This is a bit hacky, but recently found myself in a similar situation.

In my case the cache was a private ivar, so it was being loaded with a setter method which allowed me to keep track of every key I used as I set objects for the cache. Then it's a simple thing to iterate through all possible objects to check how many are still in the cache (which could be useful in the app, but likewise just needed it for unit tests).

private var elements = NSCache<NSString, AnyObject>()
private var keysUsedSoFar = Set<String>()

var count: Int {
    var count = 0
    for key in keysUsedSoFar where readers.object(forKey: key as NSString) != nil {
        count += 1
    }
        
    return count
}

func loadCache(element: AnyObject forKey key: String) {
    keysUsedSoFar.insert(key)
    elements.setObject(element, forKey: key as NSString)
}
Mercutio
  • 1,152
  • 1
  • 14
  • 33