如何计算NSDictionary对象的总大小



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

您也可以通过以下方式找到:

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

您可以尝试获取一个数组中Dictionary的所有键,然后迭代数组以查找大小,它可能会给出字典中键的总大小。

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

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

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

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

相关内容

  • 没有找到相关文章

最新更新