Where and how are Objective-C class methods stored?

I know that when an instance of an object is created on the heap, at least enough memory is allocated to accommodate the ivars object. My question is how the methods are stored by the compiler. Is there only one instance of the method code in memory? Or does the code generate the internal part of the object in memory, stored sequentially with Ivars and executed?

It seems that if this were the case, even trivial objects, such as NSString, required (relatively) a large amount of memory ( NSStringalso inherits methods from NSObject).

Or is the method stored once in memory and passed a pointer to the object that owns it?

+4
source share
2 answers

In the standard Objective-C environment, each object contains, before any other variables, a pointer to the class of which it is a member, as if the base class Object had an instance variable:

Class isa;

Each object of this class has the same pointer isa.

The class contains several elements, including a pointer to the parent class, as well as an array of method lists. These methods are implemented specifically for this class.

struct objc_class {
    Class super_class;
    ...
    struct objc_method_list **methodLists;
    ...
};

These method lists contain an array of methods:

struct objc_method_list {
    int method_count;
    struct objc_method method_list[];
};

struct objc_method {
    SEL method_name;
    char *method_types;
    IMP method_imp;
};

The type IMPhere is a pointer to a function. It points to a (one) place in memory where the implementation of the method is stored, like any other code.


. , , , , ObjC 1.0. , ; , , . , , - , , , .

, (, / ). , gory.

+8

. , . , Mach-O Apple. , , - .

"" . , , , 400 NSStrings, .

, . , , , .

+1

All Articles