Skip to content

Instantly share code, notes, and snippets.

@erisdev
Created March 11, 2012 04:09
Show Gist options
  • Save erisdev/2014978 to your computer and use it in GitHub Desktop.
Save erisdev/2014978 to your computer and use it in GitHub Desktop.
Miss +[NSObject poseAsClass:]? Don't use this, you might hurt yourself or someone you love.
#import <objc/runtime.h>
#import <stdlib.h>
// declare some of the Objective-C runtime's private parts where we can see them
typedef struct _NXMapTable NXMapTable;
extern NXMapTable *gdb_objc_realized_classes;
extern void *NXMapInsert(NXMapTable *table, const void *key, const void *value);
@implementation NSObject (Poser)
+ (void)poseAsClass:(Class)posedClass
{
int n, i;
Class *subclasses;
// refuse to pose as non-superclass
// XXX a serious implementation should probably raise an error here
if ( class_getSuperclass(self) != posedClass ) return;
// grab the list of all registered classes
n = objc_getClassList(NULL, 0);
subclasses = alloca(n * sizeof(Class));
objc_getClassList(subclasses, n);
// iterate over the entire class list and re-super all subclasses of posedClass except for this one
for ( i = 0; i < n; ++i )
if ( class_getSuperclass(subclasses[i]) == posedClass && subclasses[i] != self )
// this is a really terrible idea
class_setSuperclass(subclasses[i], self);
// good lord, we're committing identity fraud
NXMapInsert(gdb_objc_realized_classes, class_getName(posedClass), self);
}
@end
@erisdev
Copy link
Author

erisdev commented Mar 11, 2012

Come to think of it, one might wonder why I even bother checking the superclass when this entire thing is pretty much the worst idea ever.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment