2

我有两个应用程序,一个带有 UI(一个 Cocoa 应用程序)。另一个是控制台应用程序。

我的要求是在 CocoaApp 中获取用户输入并将其传递给进程到 ConsoleApp 并返回值。

我已经尝试过这样的事情,我能够发送和处理数据,但无法返回。我不能使用 NSDistibutedNotification。我用谷歌搜索并发现 NSPipe 应该可以工作,但我无法理解如何实现和使用 Pipes,请提出建议并帮助理解。

我的代码在这里:

在 CocoaApp 中:

- (IBAction)addClicked:(id)sender {

    if (self.firstNumber.stringValue.length == 0 || self.secondNumber.stringValue.length ==0) {
        NSLog(@"Enter values in both the fields");
        return;
    }

    NSString *a = self.firstNumber.stringValue;
    NSString *b = self.secondNumber.stringValue;

    NSTask *unixTask = [[NSTask alloc] init];

    [unixTask setArguments:@[a, b]];

    [unixTask setLaunchPath:@"/Users/.../ConsoleApp"];//the path

    [unixTask launch];
}

在 ConsoleApp 中:

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...

        NSArray *args = [[NSProcessInfo processInfo] arguments];
        NSLog(@"%@", args);

        if(args.count>1){
            Adder *adderObject = [Adder new];
            adderObject.aInt = [args[1] integerValue];
            adderObject.bInt = [args[2] integerValue];

            NSInteger sum = [adderObject addAwithB];

            NSLog(@"Sum = %ld", sum);

        }
    }
    return 0;
}
4

1 回答 1

0

If you want to be code signing / sandbox friendly, and do whatever you want XPC, then it's incredibly complicated, ( at least to me! ), but that doesn't matter because the work's already been done for you/me/us. Google for the sample code project "SMJobBlessXPC", based on the "SMJobBless" sample code... It works, I've run it myself, although it's a bit of a pain in the boobs-- make sure the Helper's plist has your correct code signing "common name" in the "Tools owned" key, and that all names of the Helper match up in the Helper tool and the App's Info.plist, etc. If you DON'T need signing/boxing, then I guess you could still use the sample code as a template, just uncheck the signed/boxed aspects of the project build.

于 2015-04-14T04:53:42.033 回答