So I am new to iOS and have been noticing that not only can you use . notation but there is : (colon).
My question is what is the difference between these two notations? what do they mean? When are they used? Are they interchangeable? When is it best to use which?
Thank you for any and all information on this matter.
Example:
[self.layer setBorderColor:[UIColor blackColor].CGColor];
self.layer.borderColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5].CGColor;
Edit:
I've even seen some instances where ':.' is used. What does that mean? (I don't have an example right now, if I find one I will update this post).
Side note, : is called colon. A semicolon is ;. The one you mean is colon.
What you are encountering is called "dot notation" and is relatively new in Objective-C (2007 if I remember right). At the time, and somewhat to this day, it has been controversial because of the confusion it creates.
Before dot notation was added in Objective-C 2.0, the bracket notation was the only way to call methods, and there were no properties. So your example would have been written:
[[self layer] setBorderColor:[[UIColor blackColor] CGColor]];
This is how ObjC was written for decades. When ObjC2 came out, it added a shortcut for this called "dot notation."
self.layer.borderColor = [[UIColor blackColor] CGColor];
In theory, dot notation was only supposed to be used for properties. In practice, the compiler allows you to use it any time you have a method with the correct signature. This is part of its controversy. There are now multiple syntaxes that do the same thing, and when you use one or the other is murky. That said, dot notation is wildly popular because it reduces typing slightly (and frankly because it looks slightly more like Java, which I suspect was its reason for being).
Dot notation can be confusing because it is ambiguous with struct notation. For example, you would expect the following to work:
self.frame.origin.x = 0.0;
Unfortunately, self.frame
is a method call using dot-notation, but frame.origin
and origin.x
are struct accesses, which are completely different and aren't compatible with dot notation (so the above won't compile). There is no way to know that from the code; you just have to know how frame
works.
Very long story short, though, in most cases:
self.foo <=> [self foo]
self.foo = bar <=> [self setFoo:bar]
The compiler just converts the former into the latter as a convenience to the programmer.