-
Notifications
You must be signed in to change notification settings - Fork 132
/
Copy pathUIViewController+Swizzled.m
116 lines (92 loc) · 2.66 KB
/
UIViewController+Swizzled.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
//
// UIViewController+Swizzled.m
//
// Created by Rui Peres on 12/08/2013.
// Copyright (c) 2013 Rui Peres. All rights reserved.
//
#import "UIViewController+Swizzled.h"
#import <objc/runtime.h>
@implementation UIViewController (Swizzled)
// Poor's man flag. Used to know if the methods are already Swizzed
static BOOL isSwizzed;
static NSString *logTag = @"";
+(void)load
{
isSwizzed = NO;
}
#pragma mark - Util methods
static void swizzInstance(Class class, SEL originalSelector, SEL swizzledSelector)
{
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
BOOL didAddMethod =
class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
if (didAddMethod)
{
class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod),method_getTypeEncoding(originalMethod));
}
else
{
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}
- (void)logWithLevel:(NSUInteger)level
{
NSString *paddingItems = @"";
for (NSUInteger i = 0; i<=level; i++)
{
paddingItems = [paddingItems stringByAppendingFormat:@"--"];
}
NSLog(@"%@%@-> %@", logTag, paddingItems, [self.class description]);
}
#pragma mark - SwizzMethods
- (void)printPath
{
if ([self parentViewController] == nil)
{
[self logWithLevel:0];
}
else if([[self parentViewController] isMemberOfClass:[UINavigationController class]])
{
UINavigationController *nav = (UINavigationController *)[self parentViewController];
NSInteger integer = [[nav viewControllers] indexOfObject:self];
[self logWithLevel:integer];
}
else if ([[self parentViewController] isMemberOfClass:[UITabBarController class]])
{
[self logWithLevel:1];
}
}
-(void)swizzviewDidAppear:(BOOL)animated
{
[self printPath];
// Call the original method (viewWillAppear)
[self swizzviewDidAppear:animated];
}
#pragma mark - Public methods
+ (void)swizzIt
{
// We won't do anything if it's already swizzed
if (isSwizzed)
{
return;
}
swizzInstance([self class],@selector(viewDidAppear:),@selector(swizzviewDidAppear:));
isSwizzed = YES;
}
+ (void)swizzItWithTag:(NSString *)tag
{
logTag = tag;
[self swizzIt];
}
+ (void)undoSwizz
{
// We won't do anything if it has not been Swizzed
if (!isSwizzed)
{
return;
}
isSwizzed = NO;
swizzInstance([self class],@selector(swizzviewDidAppear:),@selector(viewDidAppear:));
}
@end