I'm trying to find the size of an objective-c object. I'm using something similar to:
NSLog(@"sizeof myObject: %ld", sizeof(*myObject));
That just gives me the size of the pointer though.
What am I doing wrong?
All the compiler knows about is the pointer, which is why you're getting the size of the pointer back. To see the size of the allocated object, use one of the following code snippets:
#import <malloc/malloc.h>
// ...
NSLog(@"Size of %@: %zd", NSStringFromClass([myObject class]), malloc_size((__bridge const void *) myObject));
#import <malloc/malloc.h>
// ...
NSLog(@"size of myObject: %zd", malloc_size(myObject));
Mike Ash has a decent write-up about some of the Obj-C runtime internals on his Q&A blog: http://mikeash.com/?page=pyblog/friday-qa-2009-03-13-intro-to-the-objective-c-runtime.html
In the GNU Objective-C runtime, you can use (you must import <objc/objc-api.h>
:
class_get_instance_size ([MyClass class]);
On Mac OS X you can use (you might need to import <objc/runtime.h>
):
class_getInstanceSize ([MyClass class]);
These functions will return how much memory is required to allocate an object, it will not include memory allocated by an object when it is initialised.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With