How does alloc work in Objective C?

可紊 提交于 2019-12-20 19:43:41

问题


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 ?


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/8758609/how-does-alloc-work-in-objective-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!