NSDocument based app takes each command line argument as a filename

Discussion in 'Mac Programming' started by silvercircle, Dec 31, 2012.

  1. macrumors member

    Joined:
    Nov 18, 2010
    #1
    For each argument I supply on the command line I get a message that the application can't open files of that type.
    It is an NSDocument based application for OSX.
    I want to use the arguments later on via [[NSProcessInfo processInfo] arguments], but how do I avoid that each argument is taken as a file to open?
     
  2. macrumors regular

    Joined:
    Nov 9, 2011
    #2
    An NSDocument application is not designed to be used as a command line application. Mac OS X is a UNIX based OS. The main() function in a Mac OS app looks like this:

    Code:
    int main(int argc, char *argv[])
    {
        return NSApplicationMain(argc, (const char **) argv);
    }
    The NSDocument application thinks you are opening it by dragging a file and dropping it on the app's icon with the finder. Open and run the app by using the run button in the upper left corner of the XCode window.
     
  3. macrumors 603

    Joined:
    Aug 9, 2009
    #3
    You could write some code in main() that parses the argc/argv it's been given, and saves it for later using your own code. Then call NSApplicationMain() with a fake argc/argv that prevents NSApplicationMain() from treating the real argc/argv as filenames to open.

    Using Senor Cuete's code as an illustration:
    Code:
    int main(int argc, char *argv[])
    {
       // Your new code goes here.
    
       // Make fake argc/argv here.
    
        return NSApplicationMain( fake_argc, fake_argv);
    }
    
    There are some real and important args passed to NSDocument-based applications, so this isn't as simple as it may seem. It's possibly you won't be able to come up with a satisfactory solution. In that case, don't use the NSDocument application as a command-line tool, and instead write a separate command-line tool. It can reside in the same sub-dir as the application executable, or it can reside under Resources. I think TextWrangler and BBEdit have bundled command-line tools, so look at them.
     
  4. thread starter macrumors member

    Joined:
    Nov 18, 2010
    #4
    I guess you are right, adding a command-line tool might be the best way to go.
    Calling NSApplicationMain() with fake argc/argv is indeed not that simple, the args passed are not documented (as fas as I know). So not easy to filter them out.
    Thanks for putting me on the right track!
     

Share This Page