forked from jerrykrinock/CategoriesObjC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NSBundle+MainApp.m
55 lines (45 loc) · 1.68 KB
/
NSBundle+MainApp.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
#import "NSBundle+MainApp.h"
#import <objc/runtime.h>
// Cache for efficiency. Bundle should not move while running!
static NSBundle* mainAppBundle = nil ;
// Used static storage because cannot add ivar in a category
@implementation NSBundle (MainApp)
+ (void)load {
// Swap the implementations of +mainBundle and +replacement_mainBundle.
// When the +mainBundle message is sent to the NSBundle class object,
// +replacement_mainBundle will be invoked instead. Conversely,
// +replacement_mainBundle will invoke +mainBundle.
Method originalMethod = class_getClassMethod(self, @selector(mainBundle)) ;
Method replacedMethod = class_getClassMethod(self, @selector(replacement_mainBundle)) ;
method_exchangeImplementations(originalMethod, replacedMethod) ;
}
+ (NSBundle*)replacement_mainBundle {
NSBundle* myMainAppBundle ;
@synchronized(self) {
myMainAppBundle = mainAppBundle ;
}
if (!myMainAppBundle) {
// The following looks like we're calling ourselves into
// an infinite loop, but because of the swap, we're
// actually invoking the original +mainBundle
NSBundle* bundle = [NSBundle replacement_mainBundle] ;
NSString* mainAppBundlePath = [bundle bundlePath] ;
while (YES) {
if ([[[mainAppBundlePath lastPathComponent] pathExtension] isEqual:@"app"]) {
break ;
}
if ([mainAppBundlePath length] < 1) {
NSLog(@"Warning 263-1857 Program apparently not in a .app") ;
mainAppBundlePath = nil ;
break ;
}
mainAppBundlePath = [mainAppBundlePath stringByDeletingLastPathComponent] ;
}
myMainAppBundle = [NSBundle bundleWithPath:mainAppBundlePath] ;
@synchronized(self) {
mainAppBundle = myMainAppBundle ;
}
}
return myMainAppBundle ;
}
@end