Created
January 17, 2016 11:56
-
-
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
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
#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