-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathswizzle.m
74 lines (57 loc) · 1.71 KB
/
swizzle.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
//
// swizzle.m
// TestEnvironment
//
// Created by Gerard Meier on 2/21/17.
//
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@protocol MyInterface
-(void) Foo;
@end
@interface SuperFoo : NSObject<MyInterface> {}
@end
@implementation SuperFoo
//-(void) Foo {
// printf("SuperFoo's Foo\n");
//}
@end
@interface SuperFoo(Lurker) {}
@end
@implementation SuperFoo(Lurker)
//-(void) Foo {
// printf("Lurker's Foo\n");
//}
@end
@interface SuperFoo(MyFoo) {}
@end
@implementation SuperFoo(MyFoo)
+(void) load {
SEL sel[] = {@selector(Foo), @selector(FooBar)};
Method met[] = {class_getInstanceMethod(self, sel[0]), class_getInstanceMethod(self, sel[1])};
// Attempt to add method.
BOOL wasAppended = class_addMethod(self, sel[0], method_getImplementation(met[1]), method_getTypeEncoding(met[1]));
if(wasAppended) {
// Method was added, because it did not exist. Override the 'old' selector to do nothing. This avoids
// recursion when calling the super class within the overriden method.
Method dummy = class_getInstanceMethod(self, @selector(gerardDummyMethodImplementation));
class_replaceMethod(self, sel[1], method_getImplementation(dummy), method_getTypeEncoding(dummy));
} else {
// Append failed. This means the method already exists. In that case it's
// trivial, just swap implementations.
method_exchangeImplementations(met[0], met[1]);
}
}
-(void) FooBar {
printf("SuperFoo's Foo\n");
[self FooBar];
}
-(void)gerardDummyMethodImplementation {
// nop.
}
@end
int main(int argc, const char * argv[]) {
SuperFoo* foo = [[SuperFoo new] autorelease];
[foo Foo];
return 0;
}