6

如何计算NSDictionary对象的总大小?NSDictionary我有 3000个具有不同键的 StudentClass 对象。我想以 KB 计算字典的总大小。我用过malloc_size(),但它总是返回 24(NSDictionary包含 1 个对象或 3000 个对象) sizeof()也总是返回相同的。

4

4 回答 4

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

斯威夫特 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)
于 2013-03-18T12:06:30.500 回答
5

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

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

for(obj in keysArray)
{
    totalSize += malloc_size(obj);
}
于 2013-03-18T11:47:49.113 回答
3

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

于 2013-03-18T11:43:06.063 回答
2

如果您的字典包含标准类(例如 NSString)而不是自定义类,则转换为 NSData 可能很有用:

NSDictionary *yourdictionary = ...;
NSData * data = [NSPropertyListSerialization dataFromPropertyList:yourdictionary
    format:NSPropertyListBinaryFormat_v1_0 errorDescription:NULL];    
NSLog(@"size of yourdictionary: %d", [data length]);
于 2013-03-18T11:51:28.903 回答