tags:

views:

161

answers:

2

Is it possible to dynamically define methods in Objective-C like we would in Ruby?

[:failure, :error, :success].each do |method|
 define_method method do
    self.state = method
  end
end
A: 

I don't beleive it's possible, because Objective C is, after all, a compiled language. Your "define method" which have to add methods to the table and have a way to compile the method at run time.

Charlie Martin
Bullcrap. The Objective-C runtime implements `class_addMethod`.
Jonathan Sterling
+3  A: 

Actually it is possible to do this, although it's not supported by the obj-c syntax, the obj-c runtime provides functions that can do it. The one you want is class_addMethod, but off the top of my head i cannot remember the exact specifics of how. All the runtime methods are documented at developer.apple.com

For the hell of it I banged up a very simple example

#import <objc/objc-class.h>

@interface MyClass : NSObject {
}
@end

@implementation MyClass
@end

id myMethod(id self, SEL cmd, NSString* message)
{
    NSLog(message);
    return nil;
}

int main(int argc, char *argv[])
{

    class_addMethod([MyClass class], @selector(newMethod:), (IMP)myMethod, "v@:#");
    [[[MyClass alloc] init] newMethod:@"Hello World"];
    return 0;
}

Now strictly speaking i think myMethod should be varargs, and it just happens to be okay to do it the way i am on x86, and may fail on ppc -- but then i could be wrong.

Oh here's the awful type encoding docs

olliej