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

- by

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:

NSMutableDictionary *dictionary = [[NSMutableDictionary alloc]init];
for (int i = 0; i <= 1000; i++) {
        
    NSString *key = [[NSString alloc]initWithFormat:@"Key%i", i];
    [dictionary setObject:@47 forKey:key];
}
NSData * data = [NSPropertyListSerialization dataFromPropertyList:dictionary format:NSPropertyListBinaryFormat_v1_0 errorDescription:NULL];

NSLog(@"Size in bytes: %lu - Entries: %lu", (unsigned long)[data length], (unsigned long)dictionary.count);

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.



If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.