I need to clear some clutter in my mind to understand objc_msgSend().
Kindly be generous enough to give details answers please. :)
Here is my understand from Apple Doc.
When a message is sent to an object, the messaging function follows
the object's isa pointer to the class structure where it looks up the
method selector in the dispatch table. If it cant find the selector
there, objc_msgSend() follows the pointer to the supperclass (HERE is
confusion) and tries to climb the class hierarchy.
Here, does the superclass get memory allocated and isa pointer available for that superclass? Does the above quote says that?
If you were look at the pre-ObjC-2.0 declaration of NSObject, you'd see:
@interface NSObject <NSObject> {
Class isa;
}
Where Class is:
typedef struct objc_class *Class;
And objc_class is:
struct objc_class {
struct objc_class *isa;
struct objc_class *super_class;
const char *name;
long version;
long info;
long instance_size;
struct objc_ivar_list *ivars;
struct objc_method_list **methodLists;
struct objc_cache *cache;
struct objc_protocol_list *protocols;
};
Thus, that isa
pointer -- the first field in NSObject
, but also the first field in every subclass -- is a pointer to that objc_class
structure. The rest of the structure describes the details of that class. That super_class
field points to the objc_class
structure that describes the superclass.
When objc_msgSend()
tries to dispatch a method to, say, an NSMutableString
, it first looks through the method list of the objc_class
describing an NSMutableString
instance. If it doesn't find the method, it looks at the super_class
structure and searches there. If it can't find it there it then looks in the super_class
's super_class
.
I.e. the super_class
pointer in the structure pointed to by the isa
of any given class is a linked list up the class hierarchy all the way to NSObject
(usually). If the super_class
field is empty, that'd be a root class.
Memory allocation is, more or less, done in a similar fashion. The instance_size
field of the instance specifies the size of the instance and, thus, the amount of memory to be allocated.
More or less. All of those structures are now opaque. As Richard Ross III said in the comments you must use the introspection functions to get at the contents of these structures. This allows Apple to change the implementation details without requiring everything to be recompiled.