priore

How to invoke a method in a class via their string names

Jun 26th, 2013
559
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. + (void)invokeMethodNamed:(NSString*)methodName withObject:(id)object classNamed:(NSString*)className
  2. {
  3.                     id class = NSClassFromString(className);
  4.                     if (class) {
  5.                         SEL selector = NSSelectorFromString(methodName);
  6.                         if ([class respondsToSelector:selector]) {
  7.                             // static method +(void)
  8.                             [class performSelector:selector withObject:object];
  9.                         } else {
  10.                             // new instanced method -(void)
  11.                             id object = [[[class alloc] init] autorelease];
  12.                             if ([object respondsToSelector:selector]) {
  13.                                 [object performSelector:selector withObject:object];
  14.                             }
  15.                         }
  16.                     }
  17. }
RAW Paste Data