Skip to content

Instantly share code, notes, and snippets.

@alco
Created June 3, 2012 13:04
Show Gist options
  • Save alco/2863378 to your computer and use it in GitHub Desktop.
Save alco/2863378 to your computer and use it in GitHub Desktop.
Resource manager rudiments
#define FILE(file) \
([[NSBundle mainBundle] pathForResource:file \
ofType:nil])
#define FILE_IN_DIR(file, dir) \
([[NSBundle mainBundle] pathForResource:file \
ofType:nil \
inDirectory:dir])
#import "ResourceManager.h"
#import <objc/runtime.h>
void swizzle(id target, SEL origSel_, SEL altSel_);
@implementation NSBundle(ResourceManagerExtension)
+ (void)initialize {
swizzle(self,
@selector(pathForResource:ofType:inDirectory:),
@selector(resourcemanager_pathForResource:ofType:inDirectory:));
}
- (NSString *)pathForResource:(NSString *)name ofType:(NSString *)ext {
return [self pathForResource:name ofType:ext inDirectory:nil];
}
- (NSString *)resourcemanager_pathForResource:(NSString *)name ofType:(NSString *)ext inDirectory:(NSString *)subpath
// First, we look in ~/Library/AltBundle/, then in ~/Library/ExtResources/.
// If the subpath is not found there, we call the original implementation
// of 'pathForResource:ofType:inDirectory:'
{
NSString *filename =
([ext length]
? [name stringByAppendingFormat:@".%@", ext]
: name);
NSArray *paths =
[NSArray arrayWithObjects:
[NSString pathWithComponents:
[NSArray arrayWithObjects:
[self bundlePath], @"Library", @"AltBundle", subpath, filename, nil]],
[NSString pathWithComponents:
[NSArray arrayWithObjects:
[self bundlePath], @"Library", @"ExtResources", subpath, filename, nil]],
nil];
NSFileManager *fm = [NSFileManager defaultManager];
for (NSString *path in paths) {
if ([fm fileExistsAtPath:path])
return path;
}
return [self resourcemanager_pathForResource:name ofType:ext inDirectory:subpath];
}
@end
void swizzle(id target, SEL origSel_, SEL altSel_)
// This is an adapted version of the code from https://github.com/rentzsch/jrswizzle
{
Method origMethod = class_getInstanceMethod(target, origSel_);
if (!origMethod)
return;
Method altMethod = class_getInstanceMethod(target, altSel_);
if (!altMethod)
return;
class_addMethod(target,
origSel_,
class_getMethodImplementation(target, origSel_),
method_getTypeEncoding(origMethod));
class_addMethod(target,
altSel_,
class_getMethodImplementation(target, altSel_),
method_getTypeEncoding(altMethod));
method_exchangeImplementations(class_getInstanceMethod(target, origSel_), class_getInstanceMethod(target, altSel_));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment