Adds a new method to a class with a given name and implementation.


func class_addMethod(_ cls: AnyClass!, _ name: Selector!, _ imp: IMP!, _ types: UnsafePointer<Int8>!) -> Bool



The class to which to add a method.


A selector that specifies the name of the method being added.


A function which is the implementation of the new method. The function must take at least two arguments—self and _cmd.


An array of characters that describe the types of the arguments to the method. For possible values, see Objective-C Runtime Programming Guide > Type Encodings. Since the function must take at least two arguments—self and _cmd, the second and third characters must be “@:” (the first character is the return type).

Return Value

true if the method was added successfully, otherwise false (for example, the class already contains a method implementation with that name).


class_addMethod(_:_:_:_:) will add an override of a superclass's implementation, but will not replace an existing implementation in this class. To change an existing implementation, use method_setImplementation(_:_:).

An Objective-C method is simply a C function that take at least two arguments—self and _cmd. For example, given the following function:

void myMethodIMP(id self, SEL _cmd)
    // implementation ....

you can dynamically add it to a class as a method (called resolveThisMethodDynamically) like this:

class_addMethod([self class], @selector(resolveThisMethodDynamically), (IMP) myMethodIMP, "v@:");