有关动态绑定,目标C和方法的问题 [英] Question about dynamic binding, Objective C and methods

查看:63
本文介绍了有关动态绑定,目标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];

是静态类型"方法调用的示例,因为编译器很清楚应该使用哪种方法,因为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.

这篇关于有关动态绑定,目标C和方法的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆