objective-c:函数/方法重载?

jdl*_*jdl 1 cocoa-touch objective-c

我知道进行函数/方法重载的唯一方法是通过基类.有没有办法在没有继承的同一个类中执行它?


这是我通过继承基类来进行函数重载的唯一方法示例:

@interface class1:  NSObject
-(void) print;
@end

@implementation class1
-(void) print
{
    NSLog(@"Hello there");
}
@end



@interface  class2: class1
-(void) print: (int) x;
@end

@implementation class2
-(void) print: (int) x
{
    NSLog(@"Your number is %d", x);
}
@end



int main(void)
{
    class2 *c2 = [class2 new];

    [c2 print];
    [c2 print: 5];
}
Run Code Online (Sandbox Code Playgroud)

结果:

Hello there
Your number is 5
Run Code Online (Sandbox Code Playgroud)

Mos*_*she 8

在Objective-C中,您不能重载函数以采用不同类型的参数.例如,以下两种方法不起作用:

- (NSString *) someStringBasedOnANumber:(int)aNumber{
    //some code here
}

- (NSString *) someStringBasedOnANumber:(double)aNumber{
    //some code here
}
Run Code Online (Sandbox Code Playgroud)

最简单的解决方案是更改方法名称以遵循Apple的方法命名约定并重命名方法,如下所示:

- (NSString *) someStringBasedOnAnInt:(int)aNumber{
    //some code here
}

- (NSString *) someStringBasedOnADouble:(double)aNumber{
    //some code here
}
Run Code Online (Sandbox Code Playgroud)

方法名称应该描述方法的参数.重载违反了这个约定,所以它是不合理的.

  • 喜欢最后一段. (2认同)