Alex Rivera | Logout

Dot notation vs square brackets and casting in Objective-C

Asked 2011-06-09T12:26:39.710
11

Which of the following is best practice in Objective-C?

UITableView* view = (UITableView*) [self view];
[view setSeparatorColor:[UIColor blackColor]];
[view release];

vs.

((UITableView*) self.view).separatorColor = [UIColor blackColor];

Or is there a better way of writing this? self.view is a UIView*.

I'm asking both because I have a weird looking cast (maybe there's a better way?) and because of the following text from the official documentation, which hints that it's more than just a matter of style or personal preference:

A further advantage is that the compiler can signal an error when it detects an attempt to write to a read-only declared property. If you instead use square bracket syntax for accessing variables, the compiler—at best—generates only an undeclared method warning that you invoked a nonexistent setter method, and the code fails at runtime.

Edit
Report

2 Answers

12

Well.... dot notation compiles down to square brackets in the end, but it is down to personal preference. I personally avoid dot notation unless I am setting / accessing a scalar type, it is too easy to look at the following for instance...

view.step = 2.0;

... and not know where step is a scalar property, or has a setter method etc. I prefer to be explicit and would use...

[view setStep:2.0];

But again personal preference I guess.

answered 2011-06-09T12:31:18.563
0

You can also cast within the bracket and save yourself a line or two using this syntax:

[(UITableView*) self.view setSeparatorColor:[UIColor redColor]];
answered 2012-12-24T04:53:53.663

Your Answer