关于动态绑定、Objective C 和方法的问题

发布于 2024-11-19 06:19:04 字数 192 浏览 2 评论 0原文

根据 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

看海 2024-11-26 06:19:04

选择器代表方法名称,而不是方法签名。在以下示例中:

- (void)someMethod:(int)intParam;
- (id)someMethod:(float)floatParam;

两个方法具有相同的名称 (someMethod:),因此具有相同的选择器:@selector(someMethod:)

假设您已在名为 Foo 的类中声明了第一个方法,并在名为 Bar 的类中声明了第二个方法。然后:

Foo *foo = …;
Bar *bar = …;

[foo someMethod:42];
[bar someMethod:3.1416f];

是“静态类型”方法调用的示例,因为编译器很清楚应该使用哪个方法,因为 foobar 是静态类型的。

现在考虑以下情况:

id foobar = …;

[foobar someMethod:42];

由于 foobar 具有类型 id(通用 Objective-C 对象类型),因此编译器没有足够的信息来决定调用哪个方法。它会选择这两种方法之一,这可能很危险,具体取决于返回类型和参数类型之间的差异。这就是为什么 Apple 建议具有相同名称的方法也应该具有相同的签名。 Matt Gallagher 写了一篇关于陷阱的博客文章Objective-C 中的弱类型

A selector represents a method name, not a method signature. In the following example:

- (void)someMethod:(int)intParam;
- (id)someMethod:(float)floatParam;

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 called Bar. Then:

Foo *foo = …;
Bar *bar = …;

[foo someMethod:42];
[bar someMethod:3.1416f];

are examples of ‘static typed’ method calls since it’s clear to the compiler which method should be used because foo and bar are statically typed.

Now consider the following:

id foobar = …;

[foobar someMethod:42];

Since foobar has type id, 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文