Skip to content

Instantly share code, notes, and snippets.

@drunknbass
Created July 9, 2012 03:08
Show Gist options
  • Save drunknbass/3074015 to your computer and use it in GitHub Desktop.
Save drunknbass/3074015 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"
void SwizzleMethod(Class _class, SEL sel, IMP imp, const char *prefix) {
if (_class == nil)
return;
Method method = class_getInstanceMethod(_class, sel);
if (method == nil)
return;
const char *name = sel_getName(sel);
const char *type = method_getTypeEncoding(method);
if (prefix != NULL) {
size_t namelen = strlen(name);
size_t fixlen = strlen(prefix);
char newname[fixlen + namelen + 1];
memcpy(newname, prefix, fixlen);
memcpy(newname + fixlen, name, namelen + 1);
if (!class_addMethod(_class, sel_registerName(newname), method_getImplementation(method), type))
printf("Error: failed to rename1");
}
unsigned int count;
Method *methods = class_copyMethodList(_class, &count);
for (unsigned int index = 0; index < count; index++)
if (methods[index] == method)
goto found;
if (imp != NULL)
if (!class_addMethod(_class, sel, imp, type))
printf("Error: failed to rename2");
goto done;
found:
if (imp != NULL)
method_setImplementation(method, imp);
done:
free(methods);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment