Amogh Talpallikar
Amogh Talpallikar

Reputation: 12184

How does alloc work in 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 ?

Upvotes: 10

Views: 1643

Answers (2)

Amogh Talpallikar
Amogh Talpallikar

Reputation: 12184

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 :)

Upvotes: 2

justin
justin

Reputation: 104718

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].

Upvotes: 9

Related Questions