Skip to content

Instantly share code, notes, and snippets.

@GuanshanLiu
Forked from drunknbass/gist:3074015
Created July 10, 2012 04:17
Show Gist options
  • Save GuanshanLiu/3080963 to your computer and use it in GitHub Desktop.
Save GuanshanLiu/3080963 to your computer and use it in GitHub Desktop.
Swizzletastic
#include <objc/runtime.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "SwizzleMyNizzleProtocol.h"
BOOL SwizzleMethod(Class _class, SEL origSel, IMP altImp, char *prefix) {
if (_class == NULL || origSel == NULL || altImp == NULL) {
fprintf(stderr, "[Error] Class, SEL or IMP is NULL");
return NO;
}
Method origMethod = class_getInstanceMethod(_class, origSel);
if (origMethod == NULL) {
fprintf(stderr, "[Error] origMethod not found");
return NO;
}
if (prefix == NULL) {
prefix = "orig_";
}
const char *type = method_getTypeEncoding(origMethod);
const char *origName = sel_getName(origSel);
size_t namelen = strlen(origName);
size_t fixlen = strlen(prefix);
char *altName;
altName = (char *)malloc((fixlen + namelen + 1) * sizeof(char));
memcpy(altName, prefix, fixlen);
memcpy(altName + fixlen, origName, namelen + 1);
SEL altSel = sel_registerName(altName);
if (!class_addMethod(_class, origSel, class_getMethodImplementation(_class, origSel), type)) {
fprintf(stderr, "[Error] Failed to add origMethod");
return NO;
}
if (!class_addMethod(_class, altSel, altImp, type)) {
fprintf(stderr, "[Error] Failed to add altMethod");
return NO;
}
method_exchangeImplementations(class_getInstanceMethod(_class, origSel), class_getInstanceMethod(_class, altSel));
return YES;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment