Amogh Talpallikar
Amogh Talpallikar

Reputation: 12184

What happens when alloc or allocWithZone is called?

I wanted to know , How exactly does an Objective C object gets created. I have been reading different blog posts and apple docs but I could only find incomplete information here and there about ivar and objc_class structures ad various other runtime methods and structures.

But I still did not get, What happens when we call alloc on a Class and how are superclass data members added to the structure ?

If possible, can any one Explain this to me or point me to the source code of these methods that actually allocate memory ?

Upvotes: 3

Views: 1087

Answers (2)

user529758
user529758

Reputation:

When alloc is called, it (as any other message send) first gets transformed (by the compiler) into one of the objc_msgSend* functions. This function will get the class structure pointer as its first argument, and @selector(alloc) as its second.

Then, objc_msgSend looks up the corresponding method implementation of +[class alloc], which is, in general, not overridden (custom initialization is conceptually done in -initWith...), so it will generally be +[NSObject alloc]. It is likely that alloc simply calls +[NSObject allocWithZone:]; that function's implementation might do the following steps:

1) It finds the class' istance size (probably via class_getInstanceSize()) 2) It allocates memory, most likely using the class_createInstance() function. This function clears the allocated memory to zeroes (that's why, as the specs say, all your ivars are explicitly initialized to 0 on startup), then sets the newliy created object's isa pointer to the class structure itself. 3) The allocWithZone: methods returns the fresh object pointer to alloc 4) alloc returns the object pointer to the sender, most likely it will run into [Class initWith...:].

Hope this helps. Also, apart from the Obj-C runtime docs, don't forget to check the GNUstep NSObject implementations. That's a logic and possible way how the GNU people implemented it and how Apple might have implemented it.

Upvotes: 4

Related Questions