Reputation: 303
Fraction* myFraction=[Fraction new];
[myFraction method];
myFraction
is a pointer, it assigned with the memory address. When use the method of myFraction
, shouldn't it be used * myFraction
?
Upvotes: 1
Views: 145
Reputation: 1972
You're thinking of C. Instead, Objective-C is actually dynamically dispatched, meaning that you don't actually call functions on Objective-C objects. Rather, you "send a message" to an instance. The Objective-C runtime handles the actual translation of that message into a C function call.
In your example, [myFraction method]
actually compiles into something similar to objc_msgSend(myFraction, @selector(method))
.
The objc_msgSend()
function is the heart of Objective-C. It is hand written in assembly for each supported platform. Within this assembly call, the runtime will determine the type of the instance – Fraction
in this case – and search the known instance methods on the Fraction Class. If no method is found, it will then search the superclass of Fraction all the way up to the root (NSObject
).
Once the appropriate C-function for -[Fraction method]
is identified, objc_msgSend
will invoke it for you.
Interestingly, the resulting C function call is actually provided with two additional arguments (the myFraction
pointer, and the original method selector). These are pulled off and stored in self
and _cmd
prior to executing the code you wrote in -[Fraction method]
. This is how instance state is conveyed to instance functions! Pretty cool :)
Some reading:
https://www.mikeash.com/pyblog/friday-qa-2012-11-16-lets-build-objc_msgsend.html
Upvotes: 3