如何计算的NSDictionary对象的总大小?(How to calculate total si

2019-08-17 17:29发布

如何计算的总规模NSDictionary对象? 我曾在3000个StudentClass对象NSDictionary使用不同的密钥。 我想计算KB字典的总规模。 我用malloc_size()但它总是返回图24( NSDictionary含有任1个对象或对象3000) sizeof()也返回总是相同。

Answer 1:

你可以试着得到一个数组的字典中所有的键,然后遍历数组找到的大小,它可能给你的字典里面的键的总大小。

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

for(obj in keysArray)
{
    totalSize += malloc_size(obj);
}


Answer 2:

您还可以找到这样:

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

斯威夫特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)


Answer 3:

计算大的尺寸,最好的办法NSDictionary ,我认为,将其转换为NSData ,并得到了数据的大小。 祝好运!



Answer 4:

如果你的词典中包含的标准类(如的NSString),而不是custome的人可能会被转换为NSData的有用:

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


文章来源: How to calculate total size of NSDictionary object?