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

Rah*_*ane 7 malloc sizeof ios ios5 ios6

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

Ano*_*dya 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);
Run Code Online (Sandbox Code Playgroud)

斯威夫特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)
Run Code Online (Sandbox Code Playgroud)


nsg*_*ver 5

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

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

for(obj in keysArray)
{
    totalSize += malloc_size(obj);
}
Run Code Online (Sandbox Code Playgroud)