Created
September 28, 2014 15:07
-
-
Save RuiAAPeres/52875b29e846427814f7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//The magic method | |
-(id (^)(id,...)) getSelector:(SEL) aSelector forTarget:(id) target withFirstArgument:(id) firstArgument { | |
id (^blockName)(id,...) = ^id(id values,...) { | |
id cenas = firstArgument; | |
SEL theSelector; | |
NSMethodSignature *aSignature; | |
NSInvocation *anInvocation; | |
theSelector = aSelector; | |
aSignature = [self methodSignatureForSelector:theSelector]; | |
anInvocation = [NSInvocation invocationWithMethodSignature:aSignature]; | |
[anInvocation setSelector:theSelector]; | |
[anInvocation setTarget:self]; | |
[anInvocation setArgument:&cenas atIndex:2]; | |
NSUInteger numberOfAgurments = [aSignature numberOfArguments]; | |
NSUInteger remainingArguments = numberOfAgurments-3; | |
va_list args; | |
va_start(args, values); | |
int index = 3; | |
id value = values; | |
do | |
{ | |
[anInvocation setArgument:&value atIndex:index++]; | |
remainingArguments--; | |
} | |
while( (value = va_arg(args,id)) && (remainingArguments>0) ); | |
va_end(args); | |
[anInvocation invoke]; | |
id tempResult; | |
[anInvocation getReturnValue:&tempResult]; | |
id result = tempResult; | |
return result; | |
}; | |
return blockName; | |
} | |
-(id) sumA:(NSNumber*) a WithB:(NSNumber*) b { | |
return [NSNumber numberWithInt:([a intValue] + [b intValue])]; | |
} | |
-(id) sumA:(NSNumber*) a WithB:(NSNumber*) b withC:(NSNumber*) c{ | |
return [NSNumber numberWithInt:([a intValue] + [b intValue] + [c intValue])]; | |
} | |
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { | |
id (^blockName)(id,...) = [self getSelector:@selector(sumA:WithB:) forTarget:self withFirstArgument:@2]; | |
NSLog(@"%@",blockName(@3)); //Output: 5 | |
id (^blockName2)(id,...) = [self getSelector:@selector(sumA:WithB:withC:) forTarget:self withFirstArgument:@2]; | |
NSLog(@"%@",blockName2(@3,@4)); //Output: 9 | |
return YES; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment