关于动态绑定、Objective C 和方法的问题
根据 Apple 的 Objective C 指南,具有相同名称的方法都使用相同的选择器,并且它们需要具有相同的返回类型和参数。
然后,“静态类型”方法是例外。
那么,具有相同名称和返回类型+参数的方法是否共享一个选择器,但如果只是名称相同但返回类型和/或参数不同,它将有一个不同的选择器 - 如果您发送这样的消息到它...好吧我不知道。
According to Apple's Objective C guide, methods with the same name all use the same selector and that they need to have the same return type as well as parameters.
Then there is something about "static typed" methods being the exception.
So is it that methods with the same name and return type + parameters that share a selector, but if it is only the same name but different return type and/or parameters, it will have a different selector - that if you sent such a message to it ... OK I don't know.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
选择器代表方法名称,而不是方法签名。在以下示例中:
两个方法具有相同的名称 (
someMethod:
),因此具有相同的选择器:@selector(someMethod:)
。假设您已在名为
Foo
的类中声明了第一个方法,并在名为Bar
的类中声明了第二个方法。然后:是“静态类型”方法调用的示例,因为编译器很清楚应该使用哪个方法,因为
foo
和bar
是静态类型的。现在考虑以下情况:
由于
foobar
具有类型id
(通用 Objective-C 对象类型),因此编译器没有足够的信息来决定调用哪个方法。它会选择这两种方法之一,这可能很危险,具体取决于返回类型和参数类型之间的差异。这就是为什么 Apple 建议具有相同名称的方法也应该具有相同的签名。 Matt Gallagher 写了一篇关于陷阱的博客文章Objective-C 中的弱类型。A selector represents a method name, not a method signature. In the following example:
both methods have the same name (
someMethod:
) and, consequently, the same selector:@selector(someMethod:)
.Suppose you’ve declared the first method in a class called
Foo
and the second method in a class calledBar
. Then:are examples of ‘static typed’ method calls since it’s clear to the compiler which method should be used because
foo
andbar
are statically typed.Now consider the following:
Since
foobar
has typeid
, which is the generic Objective-C object type, the compiler doesn’t have enough information to decide which method is being called. It’ll pick one of those two methods, which can be dangerous depending on the differences between the return types and parameter types. That’s why Apple recommend that methods that have the same name should have the same signature, too. Matt Gallagher has written a blog post about the pitfalls of weak typing in Objective-C.