开发者

Question about dynamic binding, Objective C and methods

开发者 https://www.devze.com 2023-03-17 17:51 出处:网络
According to Apple\'s Objective C guide, methods with the same na开发者_运维问答me all use the same selector and that they need to have the same return type as well as parameters.

According to Apple's Objective C guide, methods with the same na开发者_运维问答me 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;

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号