0

Is there a way to get how much memory a variable is using?

I mean, I have a dictionary with images inside it and if it grows too big I want to delete some of the key/values pairs inside of it.

mdmb
  • 4,833
  • 7
  • 42
  • 90

1 Answers1

0

This is precisely what NSCache is designed to handle automatically. To your deeper question, not like you're thinking. "How much memory does X use" is a very fuzzy and complicated question, particularly when you're thinking about UIImage which can wildly change its memory usage at any time, and which includes lots of memory that isn't counted directly against your program. UIImage already does a lot of memory optimization; study its docs before you reinvent what it's already doing.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610
  • Will do, I just found it easier to implement my own global dictionary. Thanks! – mdmb May 29 '16 at 14:14
  • Note that `NSCache` offers some features that you can't reimplement in your own code. In particular, discardable content can be purged while your program is suspended if there is a low memory situation. If you try to reimplement `NSCache`, your app would be killed rather than purging its discardable content in this case. (That said, if you created your `UIImage` with `init(named:)`, then it already has discardable content which can be purged while you're suspended.) – Rob Napier May 29 '16 at 14:19
  • Is there a way to observe the cache for particular value and if the value is added to the cache then fire a function? It was easier when I created my own dictionary, as I just fired a notification in a didSet property observer. – mdmb May 29 '16 at 14:23
  • I'm not clear what `didSet` you would put on a dictionary, but I would first recommend wrapping `NSCache` in a higher-level object that HAS-A `NSCache` and uses it for storage. That way you can easily implement any special behaviors you want. Alternately (though more fragile), you can subclass `NSCache` and override `setObject(_:forKey:)`. – Rob Napier May 29 '16 at 16:46
  • 1
    I ended up reading about it a little bit more and implementing it so if a value is added to the cache I fire a notification. Anyway, your advices helped me find in the docs what I was looking for. Thanks once again! – mdmb May 29 '16 at 21:23