How does alloc work in Objective C?

后端 未结 2 1022
迷失自我
迷失自我 2021-02-08 12:06

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 hav

2条回答
  •  失恋的感觉
    2021-02-08 12:24

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

提交回复
热议问题