Skip to content

Instantly share code, notes, and snippets.

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 iamleeg/e150ec46baca67b37d70 to your computer and use it in GitHub Desktop.
Save iamleeg/e150ec46baca67b37d70 to your computer and use it in GitHub Desktop.
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@interface Mutable : NSObject
@property (nonatomic, retain) id x;
@end
@implementation Mutable
-init
{
self = [super init];
if (!self) return nil;
NSString *className = [NSString stringWithFormat:@"%@_%@",
NSStringFromClass([self class]),
[[NSUUID UUID] UUIDString]];
Class instanceClass = objc_allocateClassPair([self class], [className UTF8String], 0);
IMP getter = method_getImplementation(class_getInstanceMethod([self class], @selector(x)));
class_addMethod(instanceClass, @selector(x), getter, "@@:");
objc_registerClassPair(instanceClass);
object_setClass(self, instanceClass);
return self;
}
-class { return [Mutable class]; }
-x { return nil; }
-(void)setX:nextX
{
id(^getX)(id self, id alsoSelf) = ^(id self, id alsoSelf){ return nextX; };
IMP nextGetter = imp_implementationWithBlock(getX);
Method getterMethod = class_getInstanceMethod(object_getClass(self), @selector(x));
method_setImplementation(getterMethod, nextGetter);
}
@end
int main(int argc, char *argv[]) {
@autoreleasepool {
Mutable *a = [Mutable new];
Mutable *b = [Mutable new];
NSLog(@"%@", a.x);
a.x = @"Hello, world!";
NSLog(@"%@", a.x);
NSLog(@"%@", b.x);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment