Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to swizzle a class method on iOS?

Method swizzling works great for instance methods. Now, I need to swizzle a class method. Any idea how to do it?

Tried this but it doesn't work:

void SwizzleClassMethod(Class c, SEL orig, SEL new) {  Method origMethod = class_getClassMethod(c, orig); Method newMethod = class_getClassMethod(c, new);  if(class_addMethod(c, orig, method_getImplementation(newMethod), method_getTypeEncoding(newMethod)))     class_replaceMethod(c, new, method_getImplementation(origMethod), method_getTypeEncoding(origMethod)); else     method_exchangeImplementations(origMethod, newMethod); } 
like image 623
Ortwin Gentz Avatar asked Jul 16 '10 17:07

Ortwin Gentz


People also ask

What is swizzle iOS?

iOS Swift Tips. Swizzling (other languages call this “monkey patching”) is the process of replacing a certain functionality or adding custom code before the original code is called.

What is method swizzling and when do you use it?

Method swizzling is the process of replacing the implementation of a function at runtime. Swift, as a static, strongly typed language, did not previously have any built-in mechanism that would allow to dynamically change the implementation of a function.


1 Answers

Turns out, I wasn't far away. This implementation works for me:

void SwizzleClassMethod(Class c, SEL orig, SEL new) {      Method origMethod = class_getClassMethod(c, orig);     Method newMethod = class_getClassMethod(c, new);      c = object_getClass((id)c);      if(class_addMethod(c, orig, method_getImplementation(newMethod), method_getTypeEncoding(newMethod)))         class_replaceMethod(c, new, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));     else         method_exchangeImplementations(origMethod, newMethod); } 
like image 73
Ortwin Gentz Avatar answered Sep 21 '22 05:09

Ortwin Gentz