Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically add a class method?

Using the Objective-C Runtime, how do I add the method +layerClass to the private UIGroupTableViewCellBackground class (not to its superclass, UIView)? Note: This is only for testing (to see how UITableViewStyleGrouped sets cell backgroundView & selectedBackgroundView).

like image 770
ma11hew28 Avatar asked Feb 21 '12 12:02

ma11hew28


People also ask

How do I add a method to an existing class in Python?

The normal way to add functionality (methods) to a class in Python is to define functions in the class body. There are many other ways to accomplish this that can be useful in different situations. The method can also be defined outside the scope of the class.

What is __ new __ in Python?

The __new__() is a static method of the object class. When you create a new object by calling the class, Python calls the __new__() method to create the object first and then calls the __init__() method to initialize the object's attributes.

How do you create a dynamic class in Python?

Python Code can be dynamically imported and classes can be dynamically created at run-time. Classes can be dynamically created using the type() function in Python. The type() function is used to return the type of the object. The above syntax returns the type of object.


2 Answers

To dynamically add a class method, instead of an instance method, use object_getClass(cls) to get the meta class and then add the method to the meta class. E.g.:

UIKIT_STATIC_INLINE Class my_layerClass(id self, SEL _cmd) {
    return [MyLayer class];
}

+ (void)initialize {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class class = object_getClass(NSClassFromString(@"UIGroupTableViewCellBackground"));
        NSAssert(class_addMethod(class, @selector(layerClass), (IMP)my_layerClass, "@:@"), nil);
    });
}

You might also be able to do this easier by adding the +layerClass method to a category of UIGroupTableViewCellBackground and using a forward class definition, i.e. @class UIGroupTableViewCellBackground, to get it to compile.

like image 147
ma11hew28 Avatar answered Oct 27 '22 02:10

ma11hew28


Try this magic:

#include <objc/runtime.h>

+ (void)load {
    class_addMethod(objc_getMetaClass("UIGroupTableViewCellBackground"), 
        @selector(layerClass), (IMP)my_layerClass, "@:@");
}
like image 26
malhal Avatar answered Oct 27 '22 03:10

malhal