Byte size of an NSDictionary

偶尔善良 提交于 2019-12-22 03:57:01

问题


This may sound like a completely stupid question, but how can I get the size in bytes of an NSDictionary? Can I convert it to NSData, and then get the length of that?

Help!


回答1:


You should say more about why you care about the size of the dictionary in bytes, because the answer might be different depending.

In general, the "size" of an NSDictionary's footprint in memory is not something you can see or care about. It abstracts its storage mechanism from the programmer, and uses some form of overhead beyond the actual data it's storing.

You can, however, serialize the dictionary to NSData. If the contents of the dictionary are only "primitive" types like NSNumber, NSString, NSArray, NSData, NSDictionary, you can use the NSPropertyListSerialization class to turn it into a binary property list, which will be about the most compact byte representation of its contents that you can get:

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

If it contains other custom objects, you could use NSKeyedArchiver to archive it to an NSData, but this will be significantly larger and requires the cooperation of your custom classes.




回答2:


You can get the size of any class by calling this:

#import "objc/runtime.h"
int size = class_getInstanceSize([NSDictionary class]);

This will return you the size of the class, but not the actual size occupied by an instantiated object. If you want the size of an instantiated object:

#import "malloc/malloc.h"
int size = malloc_size(myObject);


来源:https://stackoverflow.com/questions/5207224/byte-size-of-an-nsdictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!