Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Calling a method' OR 'sending a message' in Objective C

In C or any ECMAscript based language you 'call a public method or function' on an object. But in documentation for Objective C, there are no public method calls, only the sending of messages.

Is there anything wrong in thinking that when you 'send a message' in ObjC you are actually 'calling a public method on an Object'.?

like image 797
Bachalo Avatar asked May 17 '10 20:05

Bachalo


People also ask

How messaging works in Objective-C?

In Objective-C, it is valid to send a message to nil —it simply has no effect at runtime. There are several patterns in Cocoa that take advantage of this fact. The value returned from a message to nil may also be valid: If the method returns an object, then a message sent to nil returns 0 ( nil ).

What are brackets in Objective-C?

It's actually calling a method named caption. In most cases, you don't add the "get" prefix to getters in Objective-C. Whenever you see code inside square brackets, you are sending a message to an object or a class.


1 Answers

Theoretically, they're different.

Practically, not so much.

They're different in that in Objective-C, objects can choose to not respond to messages, or forward messages on to different objects, or whatever. In languages like C, function calls are really just jumping to a certain spot in memory and executing code. There's no dynamic behavior involved.

However, in standard use cases, when you send a message to an object, the method that the message represented will usually end up being called. So about 99% of the time, sending a message will result in calling a method. As such, we often say "call a method" when we really mean "send a message". So practically, they're almost always the same, but they don't have to be.

A while ago, I waxed philosophical on this topic and blogged about it: http://davedelong.tumblr.com/post/58428190187/an-observation-on-objective-c

edit

To directly answer your question, there's usually nothing wrong with saying "calling a method" instead of "sending a message". However, it's important to understand that there is a very significant implementation difference.

(And as an aside, my personal preference is to say "invoke a method on an object")

like image 164
Dave DeLong Avatar answered Oct 16 '22 05:10

Dave DeLong