http://blog.csdn.net/zxc_3731/article/details/49867095
这样xocde会报错。
2.如果参数是基本类型的话,很可能就会这样了:
虽然我们可以有很多方法达到我们的最终目的,但是能否找到更加优雅的方式解决问题。
很简单是吧!
总所周知,oc中不像java,c++一样可以实现函数重载。
像
- - (void)test:(float)value {}
- - (void)test:(int)value {}
所以有时候如果我们想要实现一下函数重载就要混编,或者是通过一下的方法:
1.如果参数是对象的话:
- - (void)test:(id)value {
- if ([value isKindOfClass:[NSString class]]) {
- NSLog(@"NSString");
- }
- else if ([value isKindOfClass:[NSDictionary class]]) {
- NSLog(@"NSDictionary");
- }
- else if ([value isKindOfClass:[NSArray class]]) {
- NSLog(@"NSArray");
- }
- else {
- NSLog(@"摩擦摩擦");
- }
- }
- - (void)testInt:(int)value {
- NSLog(@"int");
- }
- - (void)testFloat:(double)value {
- NSLog(@"double");
- }
- - (void)testLong:(long)value {
- NSLog(@"long");
- }
现在我们来介绍下黑魔法:
__attribute__((overloadable))
然后简单写了一个demo,一看就明白它是怎么用的了
- @interface ViewController ()
- @end
- NSString * __attribute__((overloadable)) mytest(NSString *x) {return @"aa";}
- NSString * __attribute__((overloadable)) mytest(NSNumber *x) {return @"bb";}
- NSString * __attribute__((overloadable)) mytest(NSDictionary *x) {return @"cc";}
- NSString * __attribute__((overloadable)) mytest(int x) { return @"int"; }
- NSString * __attribute__((overloadable)) mytest(double x) { return @"double"; }
- NSString * __attribute__((overloadable)) mytest(long x) { return @"long"; }
- @implementation ViewController
- - (void)viewDidLoad {
- [super viewDidLoad];
- NSLog(@"%@", mytest(133333333));
- }
- @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) {
// ...
}