Last active
December 17, 2015 19:29
-
-
Save chinmaygarde/5660972 to your computer and use it in GitHub Desktop.
Create an object but change the superclass
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
id objc_createInstanceOfClassWithPlatformSuperclass(Class clasz) { | |
Class currentSuperclass = class_getSuperclass(clasz); | |
Class originalSuperclass = objc_getClassRegisteredFirst(class_getName(currentSuperclass)); | |
const char *currentClassName = [[NSString stringWithFormat:@"__%s", class_getName(clasz)] UTF8String]; | |
// Allocate a new class par | |
Class createdClass = objc_allocateClassPair(originalSuperclass, currentClassName, 0); | |
if (createdClass == Nil) { | |
// Desired class already exists. Use that shit! | |
createdClass = objc_getClass(currentClassName); | |
} else { | |
// Copy methods | |
unsigned int methodCount = 0; | |
Method* methods = class_copyMethodList(clasz, &methodCount); | |
for (int i = 0; i < methodCount; i++) { | |
Method m = methods[i]; | |
SEL name = method_getName(m); | |
IMP imp = method_getImplementation(m); | |
const char* types = method_getTypeEncoding(m); | |
class_replaceMethod(createdClass, name, imp, types); | |
} | |
if (methods) | |
free(methods); // Fly free tiny memory | |
// Register new class pair | |
objc_registerClassPair(createdClass); | |
} | |
id instance = class_createInstance(clasz, 0); | |
object_setClass(instance, createdClass); | |
return instance; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment