Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking the size of an object in Objective-C

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?

like image 750
Coocoo4Cocoa Avatar asked Apr 17 '09 19:04

Coocoo4Cocoa


2 Answers

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:

With ARC:

#import <malloc/malloc.h>

// ...

NSLog(@"Size of %@: %zd", NSStringFromClass([myObject class]), malloc_size((__bridge const void *) myObject));

Without ARC:

#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

like image 182
Jason Coco Avatar answered Nov 14 '22 06:11

Jason Coco


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.

like image 19
dreamlax Avatar answered Nov 14 '22 06:11

dreamlax