如何计算NSDictionary对象的总大小?

如何计算NSDictionary对象的总大小? 我有不同的密钥在NSDictionary 3000 StudentClass对象。 我想计算字典的总大小(以KB为单位)。 我用malloc_size()但它总是返回24( NSDictionary包含1对象或3000对象) sizeof()也总是返回相同的。

您可以尝试获取数组中字典的所有键,然后遍历数组以find大小,它可能会给出字典中键的总大小。

 NSArray *keysArray = [yourDictionary allValues]; id obj = nil; int totalSize = 0; for(obj in keysArray) { totalSize += malloc_size(obj); } 

你也可以这样find:

 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); 

计算大NSDictionary的大小的最好方法,我想,将它转换为NSData并获得数据的大小。 祝你好运!

如果你的字典包含标准的类(例如NSString)而不是客户化的,那么转换成NSData可能会有用:

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