Skip to content

Instantly share code, notes, and snippets.

@software-mariodiana
Last active July 15, 2020 20:06
Show Gist options
  • Save software-mariodiana/8d2189a73d2af7a8afaa5f700976c917 to your computer and use it in GitHub Desktop.
Save software-mariodiana/8d2189a73d2af7a8afaa5f700976c917 to your computer and use it in GitHub Desktop.
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#import <objc/message.h>
@interface MyParent : NSObject
- (NSInteger)fetchNumber;
@end
@implementation MyParent
- (NSInteger)fetchNumber
{
return 1;
}
@end
@interface MyChild : MyParent
@end
@implementation MyChild
- (NSInteger)fetchNumber
{
return 2;
}
@end
int main(int argc, char *argv[])
{
@autoreleasepool {
id parent = [[MyParent alloc] init];
NSLog(@"Parent: %ld", [parent fetchNumber]);
id child = [[MyChild alloc] init];
NSLog(@"Child: %ld", [child fetchNumber]);
IMP childMethod = [child methodForSelector:@selector(fetchNumber)];
IMP parentMethod =
class_getMethodImplementation([child superclass], @selector(fetchNumber));
NSLog(@"Child method: %p", childMethod);
NSLog(@"Parent method: %p", parentMethod);
NSInteger (*func)(id, SEL) = (void *)parentMethod;
NSInteger value = func(child, @selector(fetchNumber));
NSLog(@"This should be equal to the parent's value: %ld", value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment