7

How to calculate total size of NSDictionary object? i have 3000 StudentClass objects in NSDictionary with different keys. And i want to calculate total size of dictionary in KB. I used malloc_size() but it always return 24 (NSDictionary contain either 1 object or 3000 object) sizeof() also returns always same.

DD_
  • 7,230
  • 11
  • 38
  • 59
Rahul Mane
  • 1,005
  • 18
  • 33
  • 1
    Here is simular question: http://stackoverflow.com/questions/8223560/how-to-find-the-size-of-any-object-in-ios – Ossir Mar 18 '13 at 12:05

4 Answers4

12

You can also find this way:

Objective C

NSDictionary *dict=@{@"a": @"Apple",@"b": @"bApple",@"c": @"cApple",@"d": @"dApple",@"e": @"eApple", @"f": @"bApple",@"g": @"cApple",@"h": @"dApple",@"i": @"eApple"};

NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:dict forKey:@"dictKey"];
[archiver finishEncoding];

NSInteger bytes=[data length];
float kbytes=bytes/1024.0;
NSLog(@"%f Kbytes",kbytes);

Swift 4

let dict: [String: String] = [
    "a": "Apple", "b": "bApple", "c": "cApple", "d": "dApple", "e": "eApple", "f": "bApple", "g": "cApple", "h": "dApple", "i": "eApple"
]

let data = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWith: data)
archiver.encode(dict, forKey: "dictKey")
archiver.finishEncoding()

let bytes = data.length
let kbytes = Float(bytes) / 1024.0

print(kbytes)
nickromano
  • 918
  • 8
  • 16
Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140
5

You could try to get all the keys of the Dictionary in an array and then iterate the array to find the size, it might give you the total size of the keys inside the dictionary.

NSArray *keysArray = [yourDictionary allValues];
id obj = nil;
int totalSize = 0;

for(obj in keysArray)
{
    totalSize += malloc_size(obj);
}
nsgulliver
  • 12,655
  • 23
  • 43
  • 64
3

The best way to calculate the size of big NSDictionary, I think, would be converting it to NSData and get the size of the data. Good Luck!

Fahri Azimov
  • 11,470
  • 2
  • 21
  • 29
  • By converting to NSData can we calculate the correct size of NSDictionary object in Bytes? Or it gives the converted NSData object's size, which is not the same with NSDictionary object's size? – Shamsiddin Saidov Aug 04 '14 at 12:40
2

Might be useful to convert to NSData if your dictionary contains standard classes (eg. NSString) and not custome ones:

NSDictionary *yourdictionary = ...;
NSData * data = [NSPropertyListSerialization dataFromPropertyList:yourdictionary
    format:NSPropertyListBinaryFormat_v1_0 errorDescription:NULL];    
NSLog(@"size of yourdictionary: %d", [data length]);
nzs
  • 3,252
  • 17
  • 22