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

时间:2013-03-18 11:39:10

标签: ios ios5 ios6 malloc sizeof

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

4 个答案:

答案 0 :(得分:12)

你也可以这样找到:

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

答案 1 :(得分:4)

您可以尝试在数组中获取Dictionary的所有键,然后迭代数组以查找大小,它可能会为您提供字典中键的总大小。

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

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

答案 2 :(得分:3)

我认为,计算大NSDictionary大小的最佳方法是将其转换为NSData并获取数据的大小。祝你好运!

答案 3 :(得分:2)

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

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