Skip to content

Instantly share code, notes, and snippets.

@dmaclach
Last active November 29, 2018 05:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmaclach/ed4ec374b1da1e9f2cbe3c442723572d to your computer and use it in GitHub Desktop.
Save dmaclach/ed4ec374b1da1e9f2cbe3c442723572d to your computer and use it in GitHub Desktop.
Create an Objective C Class at runtime
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
Class myClass = objc_allocateClassPair([NSObject class], "MyClass", 0);
IMP methodIMP = imp_implementationWithBlock(^(id self) {
return @"Hello";
});
if (!class_addMethod(myClass, @selector(description), methodIMP, "@@:")) {
exit(1);
}
objc_registerClassPair(myClass);
id classInstance = [[myClass alloc] init];
NSLog(@"%@", classInstance);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment