Objective-c is a dynamic language that takes a lot of the work that static languages do at compile and link time and puts it into runtime. Objective-c is a dynamic language based on C with object-oriented features and message forwarding mechanisms, which means that it requires not only a compiler, but also a Runtime system to dynamically create classes and objects, execute compiled code, and send and forward messages. The Objective-C Runtime is a Runtime library, written basically in C and assembly, that makes C object-oriented.

Here’s an in-depth look at the Objective-C Runtime mechanism by analyzing Apple’s open-source Runtime code.

When I first learned Objective-C,

[object doSomething]
Copy the code

As a simple method call, ignoring the profound meaning of message sending, my understanding of Runtime gradually increased and I gradually understood the meaning of message sending.

With the clang compiler, when executing [object doSomething], the compiler converts it to:

clang -rewrite-objc xxx.m
SEL doSomethingSel = @selector(doSomething);
objc_msgSend(object, doSomethingSel);
Copy the code

To open objc_msgSend, you need to set the type checking parameters.

objc_msgSend(receiver, selector)
Copy the code

If the message contains parameters, then:

objc_msgSend(receiver, selector, arg1, arg2, ...)
Copy the code

If the receiver of the message can find the corresponding selector, then the specific method of the receiver object is executed directly; Otherwise, the message is either forwarded, or the corresponding implementation of the selector is temporarily added to the recipient dynamically, or it simply crashes.

You can now see that [object doSomething] is not a simple method call, because it simply determines at compile time that the message doSomething is to be sent to the receiver, and how receive will respond to that message depends on what happens at runtime.