0

我有以下 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 的情况下启动任务)都失败了。我真的很想看看我是否可以使用通知让它工作。因此,如果我能得到任何帮助,那就太好了。

4

1 回答 1

1

已读取的数据将传递给userInfokey 下字典中的通知NSFileHandleNotificationDataItem,您应该访问它而不是尝试读取更多数据。例如:

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

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

高温高压

于 2014-12-16T20:02:01.757 回答