本文介绍了在 Objective-C 应用程序之间传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我想知道是否可以在 Mac 应用程序之间传递参数,如果可以,如何传递.

I was wondering if it is possible to pass arguments between Mac applications and if it possible, how.

我知道在 Java 中可以从命令行使用以下语法:

I know that in Java is possible using the following syntax from the command line:

java JavaApp arg1 arg2 arg3 arg4

并且可以通过 main 的 args[] 数组访问它们.

And that is possible to access those through the main's args[] array.

public static void main(String[] args) {
        System.out.println("d");
        for (int i = 0; i < args.length; i++)
            System.out.println(args[i]);
}

我想将参数从 命令行 Mac 应用程序传递到 Cocoa Mac 应用程序

I want to pass the arguments from a command line Mac application to a Cocoa Mac application

推荐答案

您的所有答案都对我有用,但我找到了更适合我需求的另一种解决方案.我需要从命令行工具启动 Cocoa 应用程序,我使用以下行实现:

All your answers worked properly for me, but I found another solution that suits better my needs.I needed to launch a Cocoa app from a Command Line Tool, which I achieved with the following line:

system("nohup /PATH/Arguments.app/Contents/MacOS/Arguments argument1 argument2 &");

nohup 是 Unix 服务,它允许您将进程附加到自身,因此如果您关闭终端窗口,该进程仍然处于活动状态.

nohup is unix service that allows you to attach processes to itself so if you close the terminal window, the process remains alive.

接下来出现的问题是从 Cocoa 应用程序中捕获参数.如果 main.m 是接收它们并只返回一个 int 的参数,我将如何从 AppDelegate.m 获取参数."

Next problem that came along was capturing the arguments from within the Cocoa app. "How would I get the arguments from AppDelegate.m if main.m is the one that receives them and just returns an int."

在 Apple 的框架和库中,我找到了一个正好解决了这个问题的框架和库.这个库被称为 crt_externs.h 并包含两个有用的变量,一个用于学习参数的数量,另一个用于获取参数本身.

Among Apple's frameworks and libraries I found one that exactly solved the problem. This library is called crt_externs.h and contains two useful variables, one to learn the number of arguments, and another one to obtain the arguments themselves.

extern char ***_NSGetArgv(void);
extern int *_NSGetArgc(void);

因此,在 Cocoa 应用程序的 AppDelegate's 中,我们将编写以下代码以将参数解析为 NSString's:

So, inside at the AppDelegate's from the Cocoa app we would write the following code to parse the arguments into NSString's:

char **argv = *_NSGetArgv();
NSString *argument1 = [NSString stringWithCString:argv[1] encoding:NSUTF8StringEncoding];
NSString *argument2 = [NSString stringWithCString:argv[2] encoding:NSUTF8StringEncoding];

正如我们所见,我们直接跳到参数数组的位置 1,因为位置 0 包含路径本身:

As we can see we skip directly to the position 1 of the arguments array since position 0 contains the path itself:

argv[0] = '/PATH/Arguments.app/Contents/MacOS/Arguments'
argv[1] = 'argument1'
argv[2] = 'argument2'

感谢大家的时间和帮助.我从你们那里学到了很多.我也希望这个答案能帮助其他人:)

Thank you all for your time and help. I learned a lot from you guys. I also hope this answer helps someone else :)

干杯和快乐的编码!

这篇关于在 Objective-C 应用程序之间传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 03:00