Skip to content

Instantly share code, notes, and snippets.

@iamleeg
Last active December 17, 2015 17:09
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/5644043 to your computer and use it in GitHub Desktop.
Save iamleeg/5644043 to your computer and use it in GitHub Desktop.
Thoughts on how prototypical inheritance might be done in Objective-C. Notice that the Étoilé runtime (the predecessor to the GNUstep runtime) actually supports such things anyway.
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@interface A : NSObject
- (void)createPrivateSubclass;
@end
int main(int argc, char *argv[])
{
@autoreleasepool
{
A *a = [A new];
NSLog(@"Before: %@", [a class]);
[a createPrivateSubclass];
NSLog(@"After: %@", [a class]);
}
}
@implementation A
- (void)createPrivateSubclass
{
NSString *className = [[NSUUID UUID] UUIDString];
Class newClass = objc_allocateClassPair([self class], [className UTF8String], 0);
object_setClass(self, newClass);
}
@end
@robrix
Copy link

robrix commented May 24, 2013

Does this actually function? I note you haven’t registered the class pair after allocating it…

@robrix
Copy link

robrix commented May 24, 2013

I think this is an interesting step towards prototypal inheritance, definitely; actual cloning is of course more complex as methods have to be resolved with respect to the parent. Interesting.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment