点语法和方括号语法有什么区别? [英] What's the difference between dot syntax and square bracket syntax?

查看:295
本文介绍了点语法和方括号语法有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在经历Objective-C的一些演练,并且在很多地方引起了我的注意.我很想让他们失望.

I am going through some walkthroughs fpr Objective-C and I got to many places where I raised my eyebrows. I would love to get them down.

  1. 消息发送和方法调用是否有根本区别?使用Objective-C可以做到这两者:object.message产生与[object message]相同的结果.我认为也许不能使用点运算符策略来创建嵌套消息?

  1. Is there a fundamental difference in message sending and method calling? Objective-C lets me do both: object.message yields the same result as [object message]. I think maybe nested messages cannot be created using the dot operator strategy?

我创建了一个NSArray对象,现在我将使用NSEnumerator打印此结果:

I created an NSArray object, now I am about to print results for this using an NSEnumerator:

id myObject = [object objectEnumerator];

在while循环中迭代并打印结果. myObject type id,这意味着它是在运行时解析的,而不是在编译时解析的.我很清楚地知道我的NSArray中存储了哪些对象(它们是NSString),因此通过将myObject的类型更改为 NSString * myObject,效果很好.但是,我进行了实验,发现myObject可以是任何类型,可以是NSStringNSArrayNSEnumerator,并且任何这些都可以正常工作,完美地迭代NSArray对象并产生相同的结果结果. 这是怎么回事?

in a while loop iterating and printing results. The type of myObject is id, which means it's resolved at runtime and not compile time. I know very clearly what kind of objects are stored in my NSArray—they are NSStrings—so by changing the type of myObject to NSString * myObject, it works just fine. However, I experimented and found out that myObject can be of any type, be it NSString or NSArray or NSEnumerator, and any of these work just fine, perfectly iterating the NSArray object and yielding the same results. What's up with that?

推荐答案

我不确定您要在消息发送"和方法调用"之间进行何种区分,因为它们是两种描述同一件事.点语法只是调用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.

这篇关于点语法和方括号语法有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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