2

我想出了一种运行我的 Cocoa (GUI) 应用程序的方法。从正常双击它,或从 CLI。

我意识到当应用程序通过双击 (GUI) 启动时,它返回的参数计数 ( argc ) 为 2。

但是当从 CLI 启动时,它的argc将为1。只要我自己不提出任何参数。

这意味着我可以使用 if.. else..来确定应用程序是如何启动的。

这适用于我的应用程序,因为我不需要提出论点。

但我想知道是否有更好的方法来做到这一点。

这是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 readBuffer];

        // 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];
}

非常感谢。米

4

1 回答 1

1

除了检查 argc,您可能还需要考虑检查 argv 值本身。

对于通过双击运行的应用程序:

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

对于在命令行中运行的应用程序:

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)
于 2011-01-04T01:50:53.730 回答