When to use brackets and when to use the period in Objective-C

objective-c

Solution

The convention I have seen in new code is to use the dot for properties, and always use square brackets for messages/selectors (what you call methods). The dot was introduced in Objective-C 2.0, so the disagreement of information you find online is not entirely unexpected.

It's also entirely possible to use square brackets for everything, still (and I do):

foo = [myObject backgroundColor];
[myObject setBackgroundColor:foo];

is equivalent to

foo = myObject.backgroundColor;
myObject.backgroundColor = foo;

To reiterate, you should not be using the dot for messages, only properties.

To answer your specific question, `[UIColor clearColor]` belongs in brackets because it is not a property; it's actually a class message to `UIColor` (`+(UIColor)clearColor`).

You sound like you come from a Java world, so this might be helpful:

MyObject *foo = [[MyObject alloc] initWithAwesome:YES];    /* MyObject foo = new MyObject(TRUE); */
[foo doSomethingWithNumber:5 andString:"five"];            /* foo.doSomething(5, "five"); */
MyColor *bar = foo.faceColor;                              /* MyColor bar = foo.faceColor; */
MyColor *baz = [foo faceColor];                            /* MyColor baz = foo.faceColor; */
foo.backColor = bar;                                       /* foo.backColor = bar; */
[foo setUndersideColor:baz];                               /* foo.undersideColor = baz; */

The "setXXX" and "XXX" messages come from synthesized dynamic properties, and are an Objective-C idiom. The "dot" is simply a shorthand for calling those methods, and is roughly equivalent.

EDIT: Now that I've got some upvotes, time to make some of you reconsider >:)

I never use dots, and neither should you.

Problem

I'm a new iPhone/Objective-C developer and as I'm going through different tutorials and open source code, I am having a bit of a problem understanding when to use the square brackets "[ ]" and when to use the period " . " for accessing properties/methods of an object. For example, this code: ``` - (void)setSelected:(BOOL)selected animated:(BOOL)animated { [super setSelected:selected animated:animated]; UIColor *backgroundColor = nil; if (selected){ backgroundColor = [UIColor clearColor]; } else { backgroundColor = [UIColor whiteColor]; } self.todoTextLabel.backgroundColor = backgroundColor; self.todoTextLabel.highlighted = selected; self.todoTextLabel.opaque = !selected; self.todoPriorityLabel.backgroundColor = backgroundColor; self.todoPriorityLabel.highlighted = selected; self.todoPriorityLabel.opaque = !selected; } ``` Why does `[UIColor clearColor]` get brackets, but `todoTextLabel.backgroundColor` get the period? Could someone explain this easily for me?

Original source