Skip to content

Instantly share code, notes, and snippets.

@rhishikeshj
Created September 2, 2015 14:50
Show Gist options
  • Save rhishikeshj/f9b8a85068e990e47c04 to your computer and use it in GitHub Desktop.
Save rhishikeshj/f9b8a85068e990e47c04 to your computer and use it in GitHub Desktop.
Util class for doing reflection via objc runtime
//
// ReflectionUtil.m
//
// Created by Rhishikesh Joshi on 02/09/15.
//
#import "ReflectionUtil.h"
@import ObjectiveC;
@implementation ReflectionUtil
+ (void) callVoidClassMethod:(NSString *)methodName onClass:(NSString *)className withArgs:(NSArray *) args {
id reflectionClass = [[NSBundle mainBundle] classNamed:className];
if(reflectionClass) {
Class class = NSClassFromString(className);
SEL selector = NSSelectorFromString(methodName);
NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[class methodSignatureForSelector:selector]];
[inv setSelector:selector];
[inv setTarget:class];
int position = 2;
//arguments 0 and 1 are self and _cmd respectively, automatically set by NSInvocation
for (id arg in args) {
[inv setArgument:&arg atIndex:position];
position++;
}
[inv invoke];
}
}
+ (void) callVoidInstanceMethod:(NSString *)methodName onInstance:(id) object withArgs:(NSArray *) args {
if(object) {
SEL selector = NSSelectorFromString(methodName);
NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[object methodSignatureForSelector:selector]];
[inv setSelector:selector];
[inv setTarget:object];
int position = 2;
//arguments 0 and 1 are self and _cmd respectively, automatically set by NSInvocation
for (id arg in args) {
[inv setArgument:&arg atIndex:position];
position++;
}
[inv invoke];
}
}
+ (id) callInstanceMethod:(NSString *)methodName
onInstance:(id) object
withArgs:(NSArray *) args {
if(object) {
SEL selector = NSSelectorFromString(methodName);
NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[object methodSignatureForSelector:selector]];
[inv setSelector:selector];
[inv setTarget:object];
int position = 2;
//arguments 0 and 1 are self and _cmd respectively, automatically set by NSInvocation
for (id arg in args) {
[inv setArgument:&arg atIndex:position];
position++;
}
[inv invoke];
__unsafe_unretained id result;
[inv getReturnValue:&result];
return result;
}
return nil;
}
@end
//Usage :
// NSString *someString = @"String";
// NSString *lowerString = [ReflectionUtil callInstanceMethod:@"lowercaseString" onInstance:someString withArgs:nil];
// NSLog(@"String is %@", lowerString);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment