Objective-C Syntax and the Other Guys

Matthew Campbell, September 27, 2011

Objective-C syntax can be confusing the first few times that you see it. Some times though just comparing Objective-C to other programming languages can clear things up a bit. After all, the OOP features of Objective-C are not so different than the Other Guys.

Sending Messages vs Calling Methods or Calling Functions

Most programming languages that you are familiar probably have a notion of calling a function or calling a method.  Functions and methods are regions of code organized to do a specific task that have a forward declaration on a header file.  Generally, you use a method or function by calling it to get that something done.

So, you might typically do something like this to call a method in other programming languages:

myObject.doSomethingWithThis(thisObject);

In most programming languages this is referred to as calling a method.

In Objective-C, you would accomplish the same type of thing by doing something like this:

[myObject doSomethingWithThis:thisObject];

When you do this in Objective-C we call this sending a message.

Using Parameters in Objective-C

Here things get a little bit tricker because the way methods are declared in Objective-C is different than other languages. Usually methods are declared with a return type (like void or int), a name and then a list of parameters.

Objective-C methods are also declared with a return type but not with a name like you may be used to. Instead, Objective-C methods get a list of parameter descriptors that taken all together make up what is effectively the method name (or better yet method signature).

That means when you call a method with parameters in Objective-C it will look a bit different than what you would do in other programming languages. For instance, you might be use to something like this:

myObject.doSomethingWithThis(thisObject,thatObject,anotherObject);

But, in Objective-C you would need to include parameter descriptors in front of very parameter that you are passing in the message:

[myObject doSomethingWithThis:thisObject
                andThatObject:thatObject
            alsoAnotherObject:anotherObject];

The parameter descriptors above are: doSomethingWithThis, andThatObject, alsoAnotherObject.

Objective-C Syntax Wrap-Up

That’s some of the basic syntax of Objective-C compared to what you are probably used to. Objective-C also has some powerful features that you can leverage as well that don’t always map to other languages.

Are there any other huge differences that you can think of between Objective-C and the Other Guys?