Reputation: 2270
In macOS apps, if you need to get the path of your app or any resources in its bundle, you can of course use the mainBundle
static method of NSBundle
:
NSBundle *bundle = [NSBundle mainBundle];
NSString *appPath = [bundle bundlePath];
NSString *resourceFolderPath = [bundle resourcePath];
... etc ...
However, if the user moves your app's bundle to a different location on disk while the app is running, then this method will not work. All of the above functions will still return the bundle's old paths from before the user moved it.
How can you get the current path of your bundle or the path of any resource inside of it regardless of whether the user has moved it on disk?
So far, I've tried using NSRunningApplication
to get its current location like so:
NSRunningApplication *thisApp = [NSRunningApplication runningApplicationWithProcessIdentifier:getpid()];
NSLog(@"bundle URL: %@", [thisApp bundleURL]);
...but that too returns the old path of the bundle!
Upvotes: 2
Views: 2087
Reputation: 138051
While macOS doesn't care if you move documents around as they're open, it does care if you move applications around. This is a long-recognized issue in macOS development.
Instead of trying to fight it, app developers tend to either not care, or ask users if they want to move the application to the Applications directory at launch (since this is the most common move destination for apps). LetsMove is a project that demonstrates how you would do that.
Upvotes: 1
Reputation: 25619
Moving an application that's already running typically isn't supported. If that's a scenario you really need to support then you can do the following:
When the app is first launched, get the app's current path as you would normally and then create an NSURL bookmark for that path.
Whenever you need to know the app's current path you can resolve the NSURL bookmark you created at launch. The bookmark will resolve to app's current path, even if the app has been moved.
More info on NSURL bookmarks is available here: https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/AccessingFilesandDirectories/AccessingFilesandDirectories.html#//apple_ref/doc/uid/TP40010672-CH3-SW10
Upvotes: 2