Understand Objective-C runtime

最后都变了- 提交于 2019-12-10 11:22:51

问题


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 ?


回答1:


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.




回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!