CodingTour
iOS id类型的方法调用

来自论坛的一个问题:[在线]一个obj-c语法的问题。 直接看一个例子

@interface TestCounter : NSObject
 
- (TestCounter *)count;
 
@end
 
int main(int argc,char *argv[])
{
    @autoreleasepool{
        [(id)[TestCounter new] count];
    }
    return 0;
}

上面这个例子省略了@implementation部分,如果运行起来会看到multiple methods named 'count' found with mismatched result, parameter type or attributes.错误。

这是为什么呢?我取得了一个TestCounter的实例,但是我把它转为了id类型,然后用id类型调用了count方法,此时编译器会遍历所有的可见头的count方法,编译器当然会找到多个定义,因为count方法在NSArray,NSSet等等这些类上也有实现,而且我的TestCounter的count方法返回的是一个TestCounter对象,这和NSArray,NSSet等的count方法返回NSUInteger类型不一样,所以编译器会给你一个异常,注意看这个异常描述: multiple methods named ‘count’ found with mismatched result, parameter type or attributes.

那为什么把NSArray转成id类型调用count方法不会有错呢?因为Foundation框架的所有count方法的返回值都是一个NSUInteger类型,编译器找到的签名自然都是一样的。

如果我们把TestCounter的count的返回值也改成NSUInteger就没事了。