Last active
July 15, 2020 20:06
-
-
Save software-mariodiana/8d2189a73d2af7a8afaa5f700976c917 to your computer and use it in GitHub Desktop.
This file contains 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> | |
#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