Question

Possible Duplicate:
What's the difference between dot syntax and square bracket syntax?

I've tried using these two expressions:

  1. [[[self display] text] stringByAppendingFormat:digit];

  2. self.display.text = [self.display.text stringByAppendingFormat:digit]

Where display is a UILabel and digit is an NSString.

I intend to set digit as the label's text, but when I was trying to run the program, only #2 gave the correct results.

So what exactly is the difference between those two expressions? Is it incorrect to use square brackets for the getter and setter?

I have checked this similar question, What's the difference between dot syntax and square bracket syntax?, but still cannot figure it out.

Was it helpful?

Solution

The two syntaxes are exactly equivalent. The dot syntax is transformed into the bracket syntax by the compiler. The problem you have is that you're not setting the value in your first snippet. If you change it to:

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

You will see the same result as with the dots.

I would suggest using a temp variable to make things a tad more readable, though:

NSString * oldText = [[self display] text];
[[self display] setText:[oldText stringByAppendingFormat:@"%@", digit]];

Also note that you should have a format string as the first argument to stringByAppendingFormat:. If your digit string accidentally had any format specifiers in it, it would cause a crash. A better choice here would be stringByAppendingString: -- [oldText stringByAppendingString:digit].

OTHER TIPS

Basically there is no difference between them.

I don't know if you mystically dropped a few code, but when you use -

  [[[self display] text] stringByAppendingFormat:digit];

You haven't assigned the expression result to your variable. you should:

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

Hope it will help

Shani

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top