echo不适用于NSTask和readInBackgroundAndNotify

时间:2014-12-16 18:34:26

标签: objective-c cocoa echo nstask nsfilehandle

我有以下Obj-C代码及其日志输出。谁能告诉我为什么我没有从NSFileHandle获得任何输出?

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    [self performSelectorInBackground:@selector(startTask:) withObject:nil];
}

- (void) startTask: (id) sender
{
    NSPipe *pipe = [[NSPipe alloc] init];
    NSFileHandle *fh = pipe.fileHandleForReading;

    [fh readInBackgroundAndNotify];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(output:) name:NSFileHandleReadCompletionNotification object:fh];

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

    echoTask.standardOutput = pipe;
    echoTask.standardError = [[NSPipe alloc] init];
    echoTask.launchPath = @"/bin/echo";
    echoTask.arguments = @[@"hello world!"];

    NSLog(@"launching...");
    [echoTask launch];
    [echoTask waitUntilExit];
    NSLog(@"finished.");
}

- (void) output:(NSNotification *)notification
{
    NSFileHandle *fh = notification.object;
    NSLog(@"fh: %@", fh);

    NSString *output = [[NSString alloc] initWithData:[fh readDataToEndOfFile] encoding:NSUTF8StringEncoding];

    NSLog(@"output: '%@'", output);
}

@end

日志:

2014-12-16 10:19:58.154 SubProcess2[14893:704393] launching...
2014-12-16 10:19:58.165 SubProcess2[14893:704393] fh: <NSConcreteFileHandle: 0x6080000e9e80>
2014-12-16 10:19:58.165 SubProcess2[14893:704393] output: ''
2014-12-16 10:19:58.166 SubProcess2[14893:704393] finished.

如果我同步或使用https://stackoverflow.com/a/16274541/1015200中的方法,我可以让它工作。 任何其他技术和变体(例如没有performSelectorInBackground的启动任务)都失败了。 我真的想知道我是否可以使用通知让它工作。 所以,如果我能得到任何帮助,那将是伟大的。

1 个答案:

答案 0 :(得分:1)

已经读取的数据将传递到密钥userInfo下的NSFileHandleNotificationDataItem字典中的通知,您应该访问该数据而不是尝试读取更多数据。例如。类似的东西:

- (void) output:(NSNotification *)notification
{
   NSString *output = [[NSString alloc]
                      initWithData:notification.userInfo[NSFileHandleNotificationDataItem] 
                          encoding:NSUTF8StringEncoding];

   NSLog(@"output: '%@'", output);
}

HTH