Search code examples
objective-cobjective-c-runtime

How to dynamically add a method to a class in Objective-C?


I understand a major advantage of Objective-C over C++ is its ability to send messages to objects instead of calling its methods. Secondly you are allowed to dynamically add a method to objects.

Suppose this is my object:

@interface MyClass : NSObject
{}

- sayHello;

@end

I know my code below will work even if - sayGoodbye isn't defined, but can someone finish this code and demonstrate how Objective-C can add methods to objects at runtime?

MyClass* o = [[MyClass alloc] init];

[o sayHello  ];
[o sayGoodbye];
[o release   ];

Solution

  • The objective c runtime reference is what you need here:

    Objective-C Runtime Reference

    in particular look at the following method: class_addMethod