Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dot Notation vs Method Notation

I'm diving into iOS programming and I'm having difficulty getting my head around the idea of Dot Notation and Method Notation.

As far as I understand it, Dot Notation can be used to invoke setters/getters on properties and is much more cleaner to write/read. Method Notation is used to send messages to objects to manipulate them etc.

Could someone give me a simple explanation as to why the following two statements are essentially different and one will compile but the other will instead fail due to a syntax error.

- (IBAction)digitPressed:(UIButton *)sender 
{
   NSString *digit = [sender currentTitle];

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

}

Thanks.

like image 697
Darryl Bayliss Avatar asked Jul 08 '12 20:07

Darryl Bayliss


1 Answers

You're entering into Objective-C development at an interesting time where old syntax is being used with new syntax. Dot syntax is syntactic sugar and there are some cases where you can use it but you should not.

The following is invalid syntax. Anything where you'd use a colon (besides setters or getters), you won't use dot notation.

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

Also, you would use stringByAppendingString, not stringByAppendingFormat

You use dot notation for accessing variables, not for calling actions that will have effects.

Correct: self.foo.attributeOfMyClass

Incorrect: self.foo.downloadSomethingFromAWebsite

Ensuring you always use dot notation for accessing property values and you always use bracket notation (even when you don't have to) for calling action methods, your code will be much clearer upon a glance.

like image 148
james_womack Avatar answered Oct 31 '22 04:10

james_womack