What is preferred in Objective-c dot notation or square bracket notation?

Dvole picture Dvole · Jul 13, 2012 · Viewed 17.8k times · Source

I'm reading a book - Big Nerd Ranch iOS Programming. It says that dot notation is not recommended as it obfuscates code. I am simultaneously watching a Stanford Course for iOS programming and in it he is using dot notation extensively there. What would you recommend? I personally lean to bracket notation more.

Could you please explain how to covert this code to bracket notation?

self.display.text = [self.display.text stringByAppendingString:digit];

As I understand it should be:

[[self display] setText]:[[[self display] text] stringByAppendingString:digit];

Is it correct?

Answer

Andrew Madsen picture Andrew Madsen · Jul 13, 2012

This is a matter of personal choice. There are those that argue that dot notation makes it unclear that messages are being sent (methods are being called) since it looks just like C-style structure element access. The other side of argument is that dot notation is easier to type, easier to read, and more concise.

As someone who has been writing Objective-C since before dot notation was introduced (in Objective-C 2.0), I can understand the arguments on both sides, but prefer to use dot notation myself. That said, I do think it's important for people beginning with Objective-C to understand that dot notation syntax is converted to standard accessor method calls when compiled. I think the authors of the Big Nerd Ranch book probably have a similar attitude, and that's a big part of why they decided to use bracket notation in the book.

So in short, do what you like best. Both are valid, and the choice between the two is essentially a matter of style. No matter which you choose, make sure you understand that both styles produce equivalent compiled code.

EDIT: I forgot to answer the question about converting dot notation to bracket syntax. You're close, but what you've written is wrong and won't actually compile. It should be: [[self display] setText:[[[self display] text] stringByAppendingString:digit]] . If I were writing it I'd split it into two lines (well, really I'd use dot notation):

NSString *stringWithDigit = [[[self display] text] stringByAppendingString:digit];
[[self display] setText:stringWithDigit];

EDIT 2: It has been more than 3 years since I wrote this answer. I just wanted to note that these days, a great many more Apple framework classes have had things that were previously regular methods converted to @properties (e.g. -[NSArray count]) presumably for better Swift interop. This has led me to use dot notation even more liberally than I used to.