Skip to content

Instantly share code, notes, and snippets.

@PsychoH13
Created November 27, 2012 22:42
Show Gist options
  • Save PsychoH13/4157678 to your computer and use it in GitHub Desktop.
Save PsychoH13/4157678 to your computer and use it in GitHub Desktop.
Syntax abuse in ObjC
#import <objc/runtime.h>
#import <Foundation/Foundation.h>
@interface NSObject ()
- (id)objectForKeyedSubscript:(id)key;
@end
@interface MyMagicObject : NSObject
- (id)initWithInteger:(NSInteger)value;
- (void(^)(NSInteger))magicMethod;
@end
@implementation MyMagicObject
{
NSInteger _value;
void(^_magicBlock)(NSInteger);
}
- (id)initWithInteger:(NSInteger)value
{
if((self = [super init]))
{
_value = value;
__weak MyMagicObject *weakSelf = self;
_magicBlock = [^(NSInteger value){
MyMagicObject *self = weakSelf;
if(self == nil) return;
NSLog(@"%ld and %ld", _value, value);
} copy];
Class cls = objc_allocateClassPair(object_getClass(_magicBlock), "MagicBlockClass", 0);
IMP imp = imp_implementationWithBlock(^ id (id self, id key) {
return [NSString stringWithFormat:@"Magic string: %@", key];
});
class_addMethod(cls, @selector(objectForKeyedSubscript:), imp, "@@:@");
objc_registerClassPair(cls);
object_setClass(_magicBlock, cls);
}
return self;
}
- (void(^)(NSInteger))magicMethod;
{
return _magicBlock;
}
@end
int main(int argc, const char * argv[])
{
@autoreleasepool
{
MyMagicObject *obj = [[MyMagicObject alloc] initWithInteger:42];
obj.magicMethod(13);
NSLog(@"Result: %@", ((id)obj.magicMethod)[@"Hello"]);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment