Introducing Objective-C Code

The essential features of Objective-C are very easy to use. The idioms are simple and intuitive, and you’ll likely find they’re easy to remember.

Working with messages and properties

The code for sending a message to an object, which is equivalent to running a method in an object, looks like this:

[anObject aMessage];

This simply sends aMessage to anObject.

You can nest messages, like this:

[[anObject aMessage] anotherMessage];

This code sends aMessage to anObject and then sends anotherMessage to the result.

If aMessage takes some input values or objects, the code looks like this:

[anObject aMessage: anInput with:anotherInput andPossibly: moreInput];

“with” and “andPossibly” are part of the method name. They’re set when you (or Apple) define the method. (Some methods have very long lists of inputs.)

If aMessage returns a result, you can do this:

aResult = [anObject aMessage];

aResult is typed; when you declare aResult in your code, it’s type must match the type returned by aMessage. However, if you don’t know the type or if you don’t care about the type, you can use a generic catch-all type called id:

id aResult = [anObject aMessage]; //This always works. (But it isn’t always useful.)

genius_2c.eps

Using id is particularly helpful for managing UI events. Sometimes you want a single method that can handle events from multiple UI objects of many different types. ...

Get iOS App Development Portable Genius now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.