How to find the residing directory of a OS X application package - programmatically

前端 未结 3 1270
予麋鹿
予麋鹿 2021-01-15 16:03

I have a OS X application as a .app package which can reside in any arbitrary location in the filesystem. Is there a way to find the current path of the package programmatic

相关标签:
3条回答
  • 2021-01-15 16:35

    Building off the argv[0] version above, you can also get the path from:

        NSArray* arguments = [[NSProcessInfo processInfo] arguments];
    
        NSString* exe = [args objectAtIndex:0];
    

    from init or applicationDidFinishLaunching

    0 讨论(0)
  • You should be able to find the location of the .app by [[NSBundle mainBundle] bundleURL]; or [[NSBundle mainBundle] bundlePath];.

    However, you probably want to access resources inside the .app by going through NSBundle to locate them in most cases (this deals with issues like localization).

    Note: If you are planning to modify the application bundle; don't. You should not, can not and must not assume that you have write access to the application bundle; and if you do, something is likely very wrong.

    Edit: As a point of interest, if you are writing a C program on OS X and need to find the location of the executable; you can use a non-portable main declaration like so:

    int main (int argc, const char *argv[], const char *env[], const char *path[]) {
      // path[0] now contains the path to the executable
      // NOT PORTABLE! OS X ONLY!
      return 0;
    }
    
    0 讨论(0)
  • The bundle directory might be a problem with command line tools. So i use the following function which uses the mach-0 linker function to resolve shared libraries.

     static char* find_executable_filepath () noexcept 
     {
         char path[1];
         uint32_t size = 1;
         if (_NSGetExecutablePath(path, &size) == 0) return nullptr;
         char* res = (char*)malloc(size+1);
         if (_NSGetExecutablePath(res, &size) != 0) return nullptr;
         char* r = realpath(res, nullptr);
         free(res);
         return r; 
     }
    
    0 讨论(0)
提交回复
热议问题