Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Build a Simple iPhone App (iOS7) Animating and Intercepting Events Property Based Animation

dot syntax vs. square bracket syntax

Can I use square brackets syntax instead dot syntax for self.label.text = nil;?

3 Answers

Mike Baxter
Mike Baxter
4,442 Points

Yeah, it all comes down to personal preference in most cases. People will argue for either side. I personally like square brackets, but sometimes I'll switch to dot syntax for certain things—whichever makes the most sense (to me) in a certain context.

The thing you have to pay attention to is how the names change. In Objective-C classes, your accessor methods read like this:

// Retrieves the text
(NSString *)text {
    return whateverTheTextStringIs;
}

// Sets the text
(void)setText:(NSString *)text {
    whateverTheTextStringIs = text;
}

Of course I'm just making up variable names like "whateverTheTextStringIs." The key idea is that almost all Apple-made classes, such as NSTextLabel, have their methods set up so that calling the variable returns the value of the variable, and calling "set*" (like "setText") is a method to set that variable. But when you use dot syntax, the variable is both retrieved and set by typing the same thing.

Like this:

Getting a variable value

NSString *stringA = self.label.text;

NSString *stringB = [self label] text];

Setting a variable value

self.label.text = nil;

[[self label] setText: nil];

The square brackets are meant to be read more like reading a sentence; the dot syntax is more for convenience and brevity.

Thanks Mike, very useful explanation.

Mike Baxter
Mike Baxter
4,442 Points

You're welcome, Thiago Barbosa , glad I could help!

Stone Preston
Stone Preston
42,016 Points

you can, its a little more cumbersome though

[[self label] setText:nil];

Excellent, thank you Stone Preston.. what about self.label.text = [self.crystalBall randomNumber];?

Mike Baxter
Mike Baxter
4,442 Points

Thiago Barbosa , maybe my explanation below will help you understand how the naming scheme works. If you have questions or need clarification, let me know!

As a short answer to your question,

[[self label] setText: [[self crystalBall] randomNumber]];

You can see it gets a little messy.

Stone Preston
Stone Preston
42,016 Points

you would have to use

[[self label] setText:[[self crystalBall] randomNumber]];