我到处都读到目标c不支持方法重载但我遇到了不同的结果.我对方法重载的了解是"具有相同名称但参数不同的方法".
请试试这个:
接口文件
-(void)methodoverloading;
-(void)methodoverloading :(int)parameter;
Run Code Online (Sandbox Code Playgroud)
实施文件
-(void)methodoverloading{
NSLog(@"methodoverloading method with no Parameter");
}
-(void)methodoverloading :(int)parameter{
NSLog(@"methodoverloading method with Parameter");
}
Run Code Online (Sandbox Code Playgroud)
呼叫:
[self methodoverloading];
[self methodoverloading: 100];
Run Code Online (Sandbox Code Playgroud)
结果:OK
2014-06-21 17:16:09.272 BasicFundamentals [869:a0b]没有参数的方法过载方法2014-06-21 17:16:09.272 BasicFundamentals [869:a0b]带参数的方法过载方法
我是对的还是在某个地方出错了?谢谢
在目标C中,方法的签名包括参数.
你的两种方法:
- (void)methodoverloading
Run Code Online (Sandbox Code Playgroud)
和
- (void)methodoverloading:(int)
Run Code Online (Sandbox Code Playgroud)
有不同的签名(methodoverloadingvs. methodoverloading:),因此是不同的方法.
当人们说Objective C不支持重载时,人们的意思是你无法定义:
- (void)method:(int)arg
Run Code Online (Sandbox Code Playgroud)
和
- (void)method:(NSString *)arg
Run Code Online (Sandbox Code Playgroud)
并让编译器根据您提供的类型在它们之间进行选择.