How to find the size of any object in iOS?
First of all, I think it's clear from the above posts that the object size is given by malloc_size(myObject)
, as suggested by Legolas and also on the Mac OS reference manual:
The malloc_size(ptr) function returns the size of the memory block that backs the allocation pointed to by ptr. The memory block size is always at least as large as the allocation it backs, and may be larger.
But if you are interested in finding out the size of the dictionary, keep in mind the following point:
The dictionary stores key-value pairs and does not contain the object itself in the value part but just increases a retain count of the object that was to be "added" and keeps a reference of that object with itself. Now, the dictionary itself just contains the references to the various objects (with a key attached). So if by any chance you are looking for the object size of all the objects refered to by the dictionary, technically that would not be the size of the dictionary. The size of the dictionary would be the sum of the size of all the keys plus the size of all the value-references against the keys plus the size of the parent NSObject. If you are still interested in finding out the size of the refered objects as well, try iterating over the dictionary values array:
NSArray *myArray = [myDictionary allValues];
id obj = nil;
int totalSize = 0;
for(obj in myArray)
{
totalSize += malloc_size(obj);
}
//totalSize now contains the total object size of the refered objects in the dictionary.
Reference
I would suggest using class_getInstanceSize
and malloc_good_size
to see what it'll round up to. This will not show the ivars and whatnot inside the returned size.
#import <malloc/malloc.h>
#import <objc/runtime.h>
NSLog(@"Object Size: %zd", malloc_good_size(class_getInstanceSize([yourObject class])));
The compiler knows only about the pointer, and that is why it will always return size of the pointer. To find the size of the allocated object try something like
NSLog(@"size of Object: %zd", malloc_size(myObject));