class_addMethod(_:_:_:_:)
Adds a new method to a class with a given name and implementation.
Declaration
func class_addMethod(_ cls: AnyClass?, _ name: Selector, _ imp: IMP, _ types: UnsafePointer<CChar>?) -> BoolParameters
- cls:
The class to which to add a method.
- name:
A selector that specifies the name of the method being added.
- imp:
A function which is the implementation of the new method. The function must take at least two arguments—
selfand_cmd. - types:
An array of characters that describe the types of the arguments to the method. For possible values, see TP40008048 > TP40008048 CH100. Since the function must take at least two arguments—
selfand_cmd, the second and third characters must be “@:” (the first character is the return type).
Return Value
YES if the method was added successfully, otherwise NO (for example, the class already contains a method implementation with that name).
Discussion
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@:");See Also
Working with Classes
class_getName(_:)class_getSuperclass(_:)class_setSuperclass(_:_:)class_isMetaClass(_:)class_getInstanceSize(_:)class_getInstanceVariable(_:_:)class_getClassVariable(_:_:)class_addIvar(_:_:_:_:_:)class_copyIvarList(_:_:)class_getIvarLayout(_:)class_setIvarLayout(_:_:)class_getWeakIvarLayout(_:)class_setWeakIvarLayout(_:_:)class_getProperty(_:_:)class_copyPropertyList(_:_:)