Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does alloc work in Objective C?

Tags:

objective-c

I know that alloc is a class method which creates object of the class and points its "isa" pointer to the class and thats how messages are mapped at runtime.

and I have some idea about allocWithZone and zones.

Can anyone tell me or point me to a nice link which explains :-

How isa pointer is pointed to the right class ?

How much memory is allocated ?

How is memory for members inherited from parent class created ?

If id is a typedef for objc_object*, what does its isa pointer point to, then how does it hold anyobject because isa pointer will get us to the dispatch table which has selectors for methods but do they have anything that tells us what data-members are suppose to be there ?

like image 345
Amogh Talpallikar Avatar asked Jan 06 '12 13:01

Amogh Talpallikar


2 Answers

The compiler inserts calls through the objc runtime for you, behind the scenes. You can find the library in your include path objc/. objc/runtime.h will probably of most interest. As a bonus, a few select common messages bypass objc_msgSend with these insertions.

How isa pointer is pointed to the right class?

objc_constructInstance

How much memory is allocated?

class_createInstance
class_getInstanceSize

How is memory for members inherited from parent class created?

The memory is zeroed, and isa is set.

If id is a typedef for objc_object*, what does its isa pointer point to, then how does it hold anyobject because isa pointer will get us to the dispatch table which has selectors for methods but do they have anything that tells us what data-members are suppose to be there?

Whatever was set at initialization. ObjC object pointers are just raw memory. Unlike other languages, casting and conversion of written types is a direct set of the variable's address - there is no explicit type promotion or conversion in memory in the following construct:

MONDisplay * display = [NSString string];
NSLog(@"%@", display);

the pointer is just the same value returned by [NSString string].

like image 162
justin Avatar answered Oct 28 '22 07:10

justin


Just to add to the discussion, I received a very nice link on one of my other similar question on Objective-C internals.

http://algorithm.com.au/downloads/talks/objective-c-internals/objective-c-internals.pdf

I hope this will be of help to many who arrive here :)

like image 42
Amogh Talpallikar Avatar answered Oct 28 '22 06:10

Amogh Talpallikar