Created
June 25, 2015 19:21
-
-
Save iamleeg/e150ec46baca67b37d70 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 <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