I have read about how Objective-C runtime works, so please comment if I misunderstood something.
Let's say I have class called Person. That class may or not have method getSex.
Person *p = [[Person alloc]init];
Here the memory is allocated for Person instance (isa is created also which points to class Person), init is used to initialize Person ivar's
[p getSex];
Here objc_msgSend(Person,@selector(getSex) is called on Person class. If Person class not have such method the runtime look for that method in Person root class and so on. When the method is found IMP is called which is a pointer to method block code. Then the method is executed.
Is that correct ?
Yes, everything is correct, except the behavior of init may or may not initialize all its member variables such that the accessors return valid results, although it is reasonable to guess that it initializes properties unless told otherwise.
There's one piece that's slightly off.
The call will actually be one of these three:
objc_msgSend(p, @selector(getSex))
objc_msgSend_fpret(p, @selector(getSex))
objc_msgSend_stret(p, @selector(getSex))
One difference here is that the first argument is to the object and not to the class.
Also, since you didn't share what the getSex
method returns, it's not possible for us to know whether it will be one of the fpret
/stret
versions or not. If the method returns a double (on certain platforms), the fpret
version will be used. If the method returns a structure value (on certain platforms), then the stret
version will be used. All others will use the standard version. All of this is platform dependent in many different ways.
As the others said, allocation will create an object with all instance variables set to 0
/NULL
and a valid isa
pointer as well. Initialization methods may or may not update the instance variables with something meaningful.
来源:https://stackoverflow.com/questions/9367112/understand-objective-c-runtime