有没有更好的方法从 GUI 或命令行启动相同的应用程序
我找到了一种运行 Cocoa (GUI) 应用程序的方法。从正常的双击它, 或者从 CLI。
我意识到,当应用程序通过双击 (GUI) 启动时,它返回的参数计数 (argc) 为 2。
但是当从 CLI 启动时,它将返回 一个参数计数 (argc)。 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];
}
非常感谢。 中号
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 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];
}
Many Thanks.
M
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
除了检查 argc 之外,您可能还需要考虑检查 argv 值本身。
对于通过双击运行的应用程序:
对于在命令行中运行的应用程序:
Aside from checking the argc, you may want to consider checking the argv value itself.
for apps running by double-clicking:
for apps running in command line: