2

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 ?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

They'll have valid but not necessarily useful contents in any case -- they're set to 0 by alloc.
Yes, but well-defined does not necessarily mean valid
I.e. memory allocated for Person instance holds only isa pointer to Person class, right ?
The isa pointer will be valid - we're talking about the properties declared in the interface, which is implementation specific.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.