How to calculate the total size of an NSDictionary object?

How to calculate the total size of an NSDictionary object? I have 3,000 StudentClass objects in an NSDictionary with different keys. And I want to calculate the total size of the dictionary in KB. I used malloc_size() , but it always returns 24 ( NSDictionary contains one object or object 3000) sizeof() also returns always the same.

+6
source share
4 answers

You can try to get all the keys of the Dictionary in the array, and then iterate over the array to find the size, it can 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); } 
+4
source

You can also find this way:

Goal 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) 
+10
source

The best way to calculate the size of a large NSDictionary , I think, is to convert it to NSData and get the size of the data. Good luck

+3
source

It may be useful to convert to NSData if your dictionary contains standard classes (e.g. NSString) rather than custome:

 NSDictionary *yourdictionary = ...; NSData * data = [NSPropertyListSerialization dataFromPropertyList:yourdictionary format:NSPropertyListBinaryFormat_v1_0 errorDescription:NULL]; NSLog(@"size of yourdictionary: %d", [data length]); 
+2
source

All Articles