objective-c中实现函数重载(黑魔法:__attribute__((overloadable)))

http://blog.csdn.net/zxc_3731/article/details/49867095

总所周知,oc中不像java,c++一样可以实现函数重载。

[html]  view plain copy
  1. - (void)test:(float)value {}  
  2. - (void)test:(int)value {}  
这样xocde会报错。

所以有时候如果我们想要实现一下函数重载就要混编,或者是通过一下的方法:

1.如果参数是对象的话:

[html]  view plain copy
  1. - (void)test:(id)value {  
  2.     if ([value isKindOfClass:[NSString class]]) {  
  3.         NSLog(@"NSString");  
  4.     }  
  5.     else if ([value isKindOfClass:[NSDictionary class]]) {  
  6.         NSLog(@"NSDictionary");  
  7.     }  
  8.     else if ([value isKindOfClass:[NSArray class]]) {  
  9.         NSLog(@"NSArray");  
  10.     }  
  11.     else {  
  12.         NSLog(@"摩擦摩擦");  
  13.     }  
  14. }  
2.如果参数是基本类型的话,很可能就会这样了:
[html]  view plain copy
  1. - (void)testInt:(int)value {  
  2.     NSLog(@"int");  
  3. }  
  4. - (void)testFloat:(double)value {  
  5.     NSLog(@"double");  
  6. }  
  7. - (void)testLong:(long)value {  
  8.     NSLog(@"long");  
  9. }  
虽然我们可以有很多方法达到我们的最终目的,但是能否找到更加优雅的方式解决问题。

现在我们来介绍下黑魔法:

__attribute__((overloadable))

然后简单写了一个demo,一看就明白它是怎么用的了

[html]  view plain copy
  1. @interface ViewController ()  
  2.   
  3. @end  
  4.   
  5. NSString * __attribute__((overloadable)) mytest(NSString *x) {return @"aa";}  
  6. NSString * __attribute__((overloadable)) mytest(NSNumber *x) {return @"bb";}  
  7. NSString * __attribute__((overloadable)) mytest(NSDictionary *x) {return @"cc";}  
  8. NSString * __attribute__((overloadable)) mytest(int x) { return @"int"; }  
  9. NSString * __attribute__((overloadable)) mytest(double x) { return @"double"; }  
  10. NSString * __attribute__((overloadable)) mytest(long x) { return @"long"; }  
  11.   
  12. @implementation ViewController  
  13.   
  14. - (void)viewDidLoad {  
  15.     [super viewDidLoad];  
  16.     NSLog(@"%@", mytest(133333333));   
  17. }  
  18. @end  
很简单是吧!

超载的C函数,__attribute__((overloadable))。 重载函数都不允许有不同数量的,所以如果C函数是否适合阁下正在试图做你那得到的默认值是什么。 这里有一个。h文件有两个函数一个人为的例子,这两个被称为PrintNum

// Prints a number in the decimal base
__attribute__((overloadable)) extern void PrintNum(NSNumber *number);
// Prints a number in the specified base
__attribute__((overloadable)) extern void PrintNum(NSNumber *number, NSUInteger base);
而在m文件。:
__attribute__((overloadable)) 
void PrintNum(NSNumber *number) {
 PrintNum(number, 10);
}
__attribute__((overloadable))
void PrintNum(NSNumber *number, NSUInteger base) {
 // ...
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值