问题描述
我正在经历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.
-
消息发送和方法调用是否有根本区别?使用Objective-C可以做到这两者:
object.message
产生与[object message]
相同的结果.我认为也许不能使用点运算符策略来创建嵌套消息?
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
可以是任何类型,可以是NSString
或NSArray
或NSEnumerator
,并且任何这些都可以正常工作,完美地迭代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 NSString
s—so by changing the type of myObject
toNSString * 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.
这篇关于点语法和方括号语法有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!