开发者

Is there a better way of launching same app from GUI or Command line

I worked out a way of running my Cocoa (GUI) app. From either the normal double clicking it, Or from the CLI.

I realised that when an app launches from a double click (GUI), it returns an argument count (argc) of 2.

But when launched from the CLI it will have an argc of 1. So long as I do not put any arguments myself.

Which means I can use if.. else.. to determine how the app was launched.

This works fine for my app as I do not need to put arguments.

But I wondered if there was a better way of doing it.

Here is an example of the code in the main.m

int main (int argc, const char * argv[]) {

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    //This determins if the app is launched from the command line or app itself is opened.

    if (argc == 1) {
        //app was run from CLI
        // Create a  object
        MyClass *mMyClass;
        mMyClass = [[MyClass alloc] init];
        // Read the Buffer
        [mMyClass readBu开发者_StackOverflow社区ffer];

        // Write out file on disk
        [mMyClass createFile];
        [mMyClass doMoreStuff]; 

        [mMyClass release];
        mMyClass = nil;

    return 0;
    } else {

    //app was doubled click, (Opened)

   return NSApplicationMain(argc,  (const char **) argv);

   ;
   // */
   //  return NSApplicationMain(argc,  (const char **) argv);
   }
   [pool drain];
}

Many Thanks. M


Aside from checking the argc, you may want to consider checking the argv value itself.

for apps running by double-clicking:

1/4/11 9:43:30 AM   Untitled[605]   argc: 2
1/4/11 9:43:30 AM   Untitled[605]   argv0: /tmp/Untitled/build/Debug/Untitled.app/Contents/MacOS/Untitled
1/4/11 9:43:30 AM   Untitled[605]   argv1: -psn_0_131104

for apps running in command line:

1/4/11 9:43:44 AM   Untitled[608]   argc: 1
1/4/11 9:43:44 AM   Untitled[608]   argv0: ./Untitled
1/4/11 9:43:44 AM   Untitled[608]   argv1: (null)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜