Tag Archives: awesomeness

Adding methods to Objective-c classes during runtime

7 Jun

Why you might wonder? World domination of course!

Here goes!

#import <Foundation/Foundation.h>
#import <objc/runtime.h>

@interface MyInterface : NSObject
{
    NSString *string;
}
@property (nonatomic, retain) NSString *string;
@end

// Implementation
@implementation MyInterface
@synthesize string;

@end

// The method we want to add to class `MyInterface`
void printSelfIMP(id self, SEL _cmd, ...) {
NSLog(@"I'm off class %@ and it holds the following string: %@", [self class], [self string]);
}

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];</code>

    MyInterface *mInterface = [[[MyInterface alloc] init] autorelease];
    mInterface.string = @"Coolness";

    if([mInterface respondsToSelector:@selector(printSelf)])
        NSLog(@"I did respond to printSelf");
    else
        NSLog(@"I did not respond to printSelf");</code>

    // Add the method to `MyInterface`
    class_addMethod([MyInterface class], @selector(printSelf), (IMP)printSelfIMP, "v:@:@");

    if([mInterface respondsToSelector:@selector(printSelf)])
        NSLog(@"I did respond to printSelf");
    else
        NSLog(@"I did not respond to printSelf");

    [mInterface printSelf];

    [pool drain];
    return 0;
}

printSelfIMP is the implementation function that we want to add the class MyInterface. All implementation functions (IMP) require the following blueprint:

:type: :methodName:(id self, SEL _cmd, ...)

Once you’ve created the function implementation for your class you can add it to the interface with the method BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *type);

The last parameter,const char *type, might seem a bit weird but it describes the return type of your function and the parameter types of your function. In this case its v: from void and 2 times @: from object. Please note that the first 2 parameters must ALWAYS be id self, SEL _cmd. For more information about the type encoding go here

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: