How to test the size of an NSDictionary (in bytes)

The NSDictionary class doesn’t have a length property that can tell us how much memory is being used for storing the whole lot. Usually we don’t really care how big our variables grow – but if you’re storing that dictionary somewhere with potentially limited space (such as iCloud Key/Value storage), it may well be of interest.

You can however turn the dictionary into data and test its size like this:

Here we setup a loop that generates a dictionary and adds 1001 entries with an NSNumber literal of 47. This will give us the following information:

Size in bytes: 12954 – Entries: 1001

Note that the above only works if your dictionary has “serialisable” data such as NSNumber, NSDate, NSArray, NSDictionary, NSString or NSData (anything that can be written to a .plist file basically) – but it will not work with custom objects.

Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.

Add your voice!