点表示法与方法表示法 [英] Dot Notation vs Method Notation

查看:154
本文介绍了点表示法与方法表示法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在深入研究iOS编程,我很难理解Dot Notation和Method Notation。

I'm diving into iOS programming and I'm having difficulty getting my head around the idea of Dot Notation and Method Notation.

据我所知,Dot Notation可用于在属性上调用setter / getters,并且写入/读取更清晰。方法表示法用于向对象发送消息以操纵它们等。

As far as I understand it, Dot Notation can be used to invoke setters/getters on properties and is much more cleaner to write/read. Method Notation is used to send messages to objects to manipulate them etc.

有人可以给我一个简单的解释,说明为什么以下两个语句本质上是不同的,一个将编译但是另一个会因语法错误而失败。

Could someone give me a simple explanation as to why the following two statements are essentially different and one will compile but the other will instead fail due to a syntax error.

- (IBAction)digitPressed:(UIButton *)sender 
{
   NSString *digit = [sender currentTitle];

   self.display.text = [self.display.text stringByAppendingFormat:digit];
   self.display.text = self.display.text.stringByAppendingFormat:digit;

}

谢谢。

推荐答案

您正在使用新语法使用旧语法的有趣时间进入Objective-C开发。 Dot语法是语法糖,在某些情况下你可以使用它但你不应该使用它。

You're entering into Objective-C development at an interesting time where old syntax is being used with new syntax. Dot syntax is syntactic sugar and there are some cases where you can use it but you should not.

以下是无效的语法。你使用冒号的任何东西(除了setter或getter),你都不会使用点符号。

The following is invalid syntax. Anything where you'd use a colon (besides setters or getters), you won't use dot notation.

self.display.text = self.display.text.stringByAppendingFormat:digit;

另外,你会使用 stringByAppendingString ,而不是 stringByAppendingFormat

Also, you would use stringByAppendingString, not stringByAppendingFormat

您使用点符号来访问变量,而不是调用会产生影响的操作。

You use dot notation for accessing variables, not for calling actions that will have effects.

正确:
self.foo.attributeOfMyClass

不正确:
self.foo.downloadSomethingFromAWebsite

确保总是使用点符号来访问属性值,并且总是使用括号表示法(即使你不必须)来调用操作方法,代码一目了然会更加清晰。

Ensuring you always use dot notation for accessing property values and you always use bracket notation (even when you don't have to) for calling action methods, your code will be much clearer upon a glance.

这篇关于点表示法与方法表示法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆