有关动态绑定,目标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.
正确答案
选择器代表方法名称,而不是方法签名.在下面的示例中:
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];
是静态类型"方法调用的示例,因为编译器很清楚应该使用哪种方法,因为foo
和bar
是静态类型的.
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
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20