Skip to content

Instantly share code, notes, and snippets.

@leoschweizer
Created January 17, 2016 11:56
Show Gist options
  • Save leoschweizer/38885cb3ea641efe7fcc to your computer and use it in GitHub Desktop.
Save leoschweizer/38885cb3ea641efe7fcc to your computer and use it in GitHub Desktop.
Creating and using a class (including instance variables and methods) at runtime with Heliograph
#import <Heliograph/Heliograph.h>
static CGSize DummySizeImpl(NSObject *self, SEL cmd) {
HGInstanceVariableMirror *ivar = [[reflect(self) classMirror] instanceVariableNamed:@"_rectIvar"];
CGRect rect;
HGStructureValueMirror *value = [ivar valueIn:self];
[value readStructureValue:&rect];
return rect.size;
}
HGClassMirror *class = [reflect([NSObject class]) addSubclassNamed:@"FooBarBaz"];
HGInstanceVariableMirror *ivar = [class addInstanceVariableNamed:@"_rectIvar" withEncoding:@encode(CGRect)];
NSString *methodEncoding = [NSString stringWithFormat: @"%s%s%s", @encode(CGSize), @encode(id), @encode(SEL)];
HGMethodMirror *method = [class addMethodNamed:NSSelectorFromString(@"size") withImplementation:(IMP)DummySizeImpl andEncoding:[methodEncoding UTF8String]];
[class registerClass];
id instance = [[[class mirroredClass] alloc] init];
[ivar setValue:[NSValue valueWithCGRect:CGRectMake(0, 0, 123, 456)] in:instance];
CGSize resultSize;
[method invokeOn:instance withArguments:@[] returnValue:&resultSize];
NSLog(@"%@", NSStringFromCGSize(resultSize));
// => {123, 456}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment