5

我知道 . 是二传手的捷径。有时,我使用这种代码:

cell.textLabel.text = [NSString stringWithFormat:@"this is row %i", indexPath.row];

这按预期工作,但我想知道,写起来更好(或更正确?)

cell.textLabel.text = [NSString stringWithFormat:@"this is row %i", [indexPath row]];

或者,换句话说,我应该只将点语法与 = 运算符一起使用,例如

aTextField.text = @"whatever";

欢迎任何链接/文档,谢谢:)

PS。如果您没有看到标签,我在这里谈论的是 iOS。

4

5 回答 5

6

点 (.) 不仅是 setter 的快捷方式,它也是 getter 的快捷方式。您也可以使用点作为吸气剂。没有问题,这也不是不好的做法。来自Obj-C 2.0 编程指南,“您可以使用点语法调用访问器方法,使用与访问结构元素相同的模式。点语法纯粹是“语法糖””。请注意,它说的是访问器方法,而不仅仅是设置器。

于 2011-01-20T10:57:35.797 回答
4

这是一个品味问题。

由于各种原因,我不喜欢使用点语法:

  • 使用点语法时,很难仅在代码中找到设置值的位置。搜索 setValue:比搜索 .value 容易得多

  • 作为一名长期的 C 程序员,我的大脑被连接到将点语法与访问结构成员联系起来。我发现在不同的范围内习惯点语法相当困难。

  • setXY: 语法更接近自然语言。让阅读别人的代码变得更加容易。

于 2011-01-20T11:20:46.660 回答
3

“。” 是访问 a 的快捷方式@property(顺便说一下,它可能是readonly)。从语法的角度来看,这是 getter 还是 setter 取决于操作数的位置:

self.enabled = NO; // setter
BOOL isEnabled = self.enabled; // getter
self.selected = self.enabled = NO; // this is OK too
于 2011-01-20T11:00:14.810 回答
1

这是编码风格,所以两者都不是更好。

我会注意两件事。

作为一个长期的Objective C代码,我更喜欢[indexPath row],因为它与代码的其余部分一致,对于一组我会使用[aTextField setText:@“whatever”]

但是如果你需要使用 . 在同一段代码中通过方法表示法访问同一变量的键路径表示法似乎很奇怪。

苹果文档

Objective-C 提供了一个点 (.) 运算符,它提供了一种紧凑且方便的语法,您可以将其用作方括号表示法 ([]s) 的替代方法来调用访问器方法。

myInstance.value = 10;
printf("myInstance value: %d", myInstance.value);

点语法纯粹是“语法糖”——编译器将其转换为访问器方法的调用(因此您实际上并没有直接访问实例变量)。上面的代码示例完全等同于以下内容:

[myInstance setValue:10]; printf("myInstance value: %d", [myInstance value]);
于 2011-01-20T11:00:37.620 回答
-2

Using the dot syntax is not coding style or a matter of taste!

The dot syntax is for accessing properties. The message sending syntax is for dispatching methods. They are conceptually two different things. Legacy and backwards compatibility to Objective-C 1.0 unfortunately makes them interchangeable, which has caused allot of confusion.

Weather to user the dot-syntax or not is dead simple:

  • If a public header declares something as property, then access it as a property using the dot-syntax, as the author of the interface explicitly intended!
  • If a public header declares something as a method, then access it using the message sending syntax, as the author of the interface explicitly intended!
  • Make NO exceptions.

The hard question is, should you declare something as a property, and thus tell your clients that doit-syntax should be used, or should you declare a method? The simple answer is:

  • Use properties for states (is something).
  • Use methods for behaviors (do/calculate something).

Another rule of thumb is that properties should be self-contained, there should be no other way to change the value of the property but to set the property itself. This is Not a hard rule, use common sense, many sensible exceptions exist. For example a hidden property that can be changed with setHidden:animated: method.

于 2011-01-20T12:08:08.373 回答