I've noticed some weird behavior with NSBundle when using it in a command-line program. If, in my program, I take an existing bundle and make a copy of it and then try to use pathForResource to look up something in the Resources folder, nil is always returned unless the bundle I'm looking up existed before my program started. I created a sample app that replicates the issue and the relevant code is:
int main(int argc, char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *exePath = [NSString stringWithCString:argv[0]
encoding:NSASCIIStringEncoding];
NSString *path = [exePath stringByDeletingLastPathComponent];
NSString *templatePath = [path stringByAppendingPathComponent:@"TestApp.app"];
// This call works because TestApp.app exists before this program is run
NSString *resourcePath = [NSBundle pathForResource:@"InfoPlist"
ofType:@"strings"
inDirectory:templatePath];
NSLog(@"NOCOPY: %@", resourcePath);
NSString *copyPath = [path stringByAppendingPathComponent:@"TestAppCopy.app"];
[[NSFileManager defaultManager] removeItemAtPath:copyPath
error:nil];
if ([[NSFileManager defaultManager] copyItemAtPath:templatePath
toPath:copyPath
error:nil])
{
// This call will fail if TestAppCopy.app does not exist before
// this program is run
NSString *resourcePath2 = [NSBundle pathForResource:@"InfoPlist"
ofType:@"strings"
inDirectory:copyPath];
NSLog(@"COPY: %@", resourcePath2);
[[NSFileManager defaultManager] removeItemAtPath:copyPath
error:nil];
}
[pool release];
}
For the purpose of this test app, let's assume that TestApp.app already exists in the same directory as my test app. If I run this, the 2nd NSLog call will output: COPY: (null)
Now, if I comment out the final removeItemAtPath call in the if statement so that when my program exits TestAppCopy.app still exists and then re-run, the program will work as expected.
I've tried this in a normal Cocoa application and I can't reproduce the behavior. It only happens in a shell tool target. Can anyone think of a reason why this is failing?
BTW: I'm trying this on 10.6.4 and I haven't tried on any other versions of Mac OS X.