29,031
社区成员
发帖
与我相关
我的任务
分享
#import <Foundation/Foundation.h>
@interface A:NSObject
-(void)mul:(double)x;
-(void)show;
@end
@implementation A
-(void)mul:(double)x{
printf("%f\n",100.001 * x);
}
-(void)show{
NSLog(@"[A obj]i : %f",100.001);
}
@end
@interface B:NSObject
-(void)mul:(int)x;
-(void)show;
@end
@implementation B
-(void)mul:(int)x{
printf("%d\n",10000 * x);
}
-(void)show{
NSLog(@"[B obj]i : %d",10000);
}
@end
int main(int argc,char *argv[])
{
@autoreleasepool{
id obj = [[A alloc] init];
[obj show];
[obj mul:123.12];
}
return 0;
}
@interface TestCounter : NSObject
- (TestCounter *)count;
@end
int main(int argc,char *argv[])
{
@autoreleasepool{
// id obj = [[A alloc] init];
// [obj show];
// [obj mul:123.12];
[(id)[TestCounter new] count];
}
return 0;
}
这个例子一样会报同样的错误,这是为什么呢?我取得了一个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呢?你可以试试。
在这版块待了这么久,很少见有人问OC运行时和编译时的问题