Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register / unregister for protocol at runtime?

Is there a proper way to unregister and register view controller to protocol?

like image 280
Devfly Avatar asked Dec 18 '25 14:12

Devfly


1 Answers

To formally conform to a protocol:

class_addProtocol([MyViewController class], @protocol(SomeProtocol));

Even more dynamically:

class_addProtocol(objc_getClass("MyViewController"), objc_getProtocol("SomeProtocol"));

To actually add method implementations to a class:

// - (int)someMethod:(int)arg;
int someMethod(id self, SEL _cmd, int arg)
{
    return arg * 2;
}

class_addMethod([MyViewController class], @selector(someMethod:), (IMP)someMethod, "i@:i");

Beware the method signature (4th argument to class_addMethod()) in this case, see the documentation for further info.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!