Tuesday, February 17, 2009

Objective-C Message Expressions

One of biggest stumbling blocks for developers new to Objective-C always always seems to be message expression syntax. So I thought I'd throw together a quick mini-tutorial for anyone who may be wrestling with this.

The basic syntax is deceptively easy:

[receiver message]

The receiver is the object or class we want to send the message to. The message is a selector (method name) of the message we want to send, along any arguments.

So for example, the following line of code sends a message to the NSString class asking it to return a new instance of itself:

NSString *myString = [NSString string];

Admittedly this is a rather silly bit of code in that it creates an empty immutable string, rarely a useful thing--but at least it's simple! This message expression sends a string message to the NSString class. The resulting new instance of NSString is then stored in the local variable myString.

Message expression syntax gets just slightly trickier when we want to include an argument value as part of the message. For example, usually when we create an immutable string we want it to have a value.

NSString *myString = [NSString stringWithString:@"Hello World!"];

What's tricky but not obvious here is that though a colon character (':') is required before an argument, syntactically it's not a delimiter; it's part of the method name.

So the name of the method is stringWithString:, rather than stringWithString. Seems like a trivial distinction, but just wait till we have more than one argument!

NSString *myString = [NSString stringWithCString:"Hello World!"
encoding:NSUTF8StringEncoding];

(Note that the linebreak here is not syntactically meaningful, since all whitespace is ignored by the compiler except as a delimiter between tokens.)

To be continued...

No comments: