• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

有关动态绑定,目标C和方法的问题

用户头像
it1352
帮助1

问题说明

根据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.

正确答案

#1

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

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

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

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

both methods have the same name (someMethod:) and, consequently, the same selector: @selector(someMethod:).

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

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];

是静态类型"方法调用的示例,因为编译器很清楚应该使用哪种方法,因为foobar是静态类型的.

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.

现在考虑以下几点:

id foobar = …;

[foobar someMethod:42];

由于foobar具有类型id(这是通用的Objective-C对象类型),因此编译器没有足够的信息来确定要调用哪种方法.它将选择这两种方法之一,根据返回类型和参数类型之间的差异,这可能很危险.因此,Apple建议名称相同的方法也应具有相同的签名.马特·加拉格尔(Matt Gallagher)写了一篇有关 Objective-C中的弱类型输入.

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.

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfieab
系列文章
更多 icon
同类精品
更多 icon
继续加载