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

既に読み取られたデータはuserInfo、 key の下のディクショナリの通知に渡されNSFileHandleNotificationDataItemます。これにアクセスし、それ以上データを読み取ろうとしないでください。例:

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

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

HTH

于 2014-12-16T20:02:01.757 に答える