【问题标题】:How to calculate total size of NSDictionary object?如何计算 NSDictionary 对象的总大小?
【发布时间】:2013-03-18 11:39:09
【问题描述】:

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

【问题讨论】:

标签: ios ios5 ios6 malloc sizeof


【解决方案1】:

你也可以这样找到:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      • 通过转换为 NSData 我们可以计算出正确的 NSDictionary 对象的字节大小吗?还是给出转换后的 NSData 对象的大小,与 NSDictionary 对象的大小不一样?
      【解决方案4】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-05-15
        • 2014-05-17
        • 1970-01-01
        • 1970-01-01
        • 2018-01-29
        • 2015-02-26
        • 2017-07-19
        相关资源
        最近更新 更多