0

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.

AndIWonder
  • 43
  • 2

1 Answers1

5

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.

  • Ah... Thank you. Thank you. Just have to be careful around 'id' type variables then, and well, avoid naming two methods the same name if they are not "related" and have the same signature. PS:I really should register, so I can vote. – AndIWonder Jul 07 '11 at 10:03
  • @And It’s not a problem if the methods have the same signature. It can be a problem if the methods have same name but _different_ signature. And even if you don’t declare your variables as `id`, there are several framework methods whose return type is `id`, so you might be getting into trouble without noticing it. –  Jul 07 '11 at 10:08
  • Thanks for the warning. Came from Java where the compiler does everything in it's power to prevent you from shooting yourself in the foot. The loose typing here is a bit of a culture shock. LOL – AndIWonder Jul 08 '11 at 00:20
  • Hi, @Bavarious, There's still one thing confusing me that why the runtime can not bind the method to the right object even the object is an `id`? to my understanding, `dynamic binding` or `dynamic typing` is that the compiler has no way of knowing what object behind an `id`, but the runtime is supposed to know that and choose the right object as the receiver of the message. but when the runtime can't do that? – neevek Feb 27 '12 at 05:19