且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

点语法和方括号语法有什么区别?

更新时间:2021-08-19 04:07:25

我不确定您要在消息发送"和方法调用"之间进行何种区分,因为它们是两种描述同一件事.点语法只是调用getter和setter的快捷方式,即:

I'm not sure what kind of distinction you're trying to make between "message sending" and "method calling", since they're two ways of describing the same thing. The dot syntax is just a shortcut for calling getters and setters, that is:

[foo length]
foo.length

完全相同,如下:

[foo setLength:5]
foo.length = 5

通常,仅在使用getter和setter时才应使用点语法.对于所有其他方法调用,请使用方括号语法.

You should generally only use the dot syntax when you're using getters and setters; use the square bracket syntax for all of your other method calls.

您的第二个问题:这是动态键入的工作方式.您在代码中放入的任何类型声明都是对编译器的提示.只要对象响应它们,您的Objective-C方法调用将始终有效.

For your second question: this is how dynamic typing works. Any type declarations you put in your code are hints to the compiler; your Objective-C method calls will always work as long as the objects respond to them.