Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate total size of NSDictionary object?

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.

like image 729
Rahul Mane Avatar asked Mar 18 '13 11:03

Rahul Mane


People also ask

What is a NSDictionary object?

An object representing a static collection of key-value pairs, for use instead of a Dictionary constant in cases that require reference semantics.

How do you set a value in NSDictionary?

You have to convert NSDictionary to NSMutableDictionary . You have to user NSMutableDictionary in place of the NSDictionary . After that you can able to change value in NSMutableDictionary . Save this answer.

Does NSDictionary retain objects?

An NSDictionary will retain it's objects, and copy it's keys. Here are some effects this has had on code I've worked on. Sometimes you get the same object you put in, sometimes not. Immutable objects are optimized to return themselves as a copy .

How do you append NSMutableDictionary?

Use NSMutableDictionary addEntriesFromDictionary to add the two dictionaries to a new mutable dictionary. You can then create an NSDictionary from the mutable one, but it's not usually necessary to have a dictionary non-mutable. Save this answer.


2 Answers

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)
like image 53
Anoop Vaidya Avatar answered Sep 18 '22 14:09

Anoop Vaidya


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);
}
like image 28
nsgulliver Avatar answered Sep 19 '22 14:09

nsgulliver