点符号vs方括号和在Objective-C中投射 [英] Dot notation vs square brackets and casting in Objective-C
问题描述
以下哪一个是Objective-C的最佳实践?
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];
还是有更好的写法吗? self.view
是一个 UIView *
。
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:
另一个优点是,当编译器检测到尝试写入只读的声明属性时,它可以发出错误信号。如果你使用方括号语法访问变量,编译器最多只能生成一个未声明的方法警告你调用了一个不存在的setter方法,并且代码在运行时失败。
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.
推荐答案
好吧...点符号最后编译成方括号,但它是由个人喜好。除非我设置/访问标量类型,否则我个人避免使用圆点符号。例如:...
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;
...不知道step是标量属性还是setter方法等。更喜欢使用...
... 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];
但我再想想个人喜好。
这篇关于点符号vs方括号和在Objective-C中投射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!