gpt4 book ai didi

objective-c - 谁能根据 Apple Objective-C 文档的这段摘录解释选择器?

转载 作者:太空狗 更新时间:2023-10-30 03:38:03 25 4
gpt4 key购买 nike

来自 Apple Objective-C 文档,加粗的相关部分:

Method Return and Parameter Types

The messaging routine has access to method implementations only through selectors, so it treats all methods with the same selector alike. It discovers the return type of a method, and the data types of its parameters, from the selector. Therefore, except for messages sent to statically typed receivers, dynamic binding requires all implementations of identically named methods to have the same return type and the same parameter types. (Statically typed receivers are an exception to this rule because the compiler can learn about the method implementation from the class type.)

Although identically named class methods and instance methods are represented by the same selector, they can have different parameter types and return types.

我一遍又一遍地阅读这个 block ,但我似乎无法克服似乎矛盾的地方。首先,它说由于动态绑定(bind),同名方法的所有实现都需要具有相同的返回类型和参数类型。

因为它对待具有相同选择器的所有方法都一视同仁,这是否意味着无论我有多少不同的对象,如果它们都有一个 EatCake() 方法,那么它们将共享 EatCake 的相同选择器?如果是这样,那么为什么它们必须具有相同的参数和返回类型?

然后在下一部分中说虽然它们由相同的选择器表示,但它们可以具有不同的参数类型和返回类型。所以现在我完全糊涂了,我以为它只是说事实并非如此。

我不认为这是一个错误,我希望我只是不理解这两个陈述之间的区别。

谁能帮我解决这个问题?

最佳答案

不要求具有相同选择器的所有方法都具有相同的参数和返回类型。选择器只是一个标识方法的名称,没有任何附加信息。

问题是当你调用一个方法时,编译器必须知道参数和返回类型是什么,这样它才能为你执行类型检查。当摘录谈到动态接收器时,它是在谈论具有 id 类型的变量和发送到返回 id 的方法结果的消息。由于这只是告诉编译器它是一个对象,而没有告诉编译器它是什么类,所以它无法确定应该使用哪个类来确定参数和返回类型。因此,它可以知道的唯一方法是该选择器的所有使用是否具有相同的参数和返回类型。

摘录还解释了静态类型接收器的异常,这意味着您为变量类型指定了某个类,例如 NSString *myString。由于编译器知道对象必须是 NSString 对象,它知道使用该类的参数和返回类型,因此不同类的对象不需要相同。

这一切对运行时绝对没有影响。当您调用一个方法时,运行时会获取该对象的实际类,并使用它来找到要调用的正确实现。它不执行类型检查,因此它不关心参数和返回类型是什么。

关于objective-c - 谁能根据 Apple Objective-C 文档的这段摘录解释选择器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7721011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com