我有以下 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 的情况下启动任务)都失败了。 我真的很想看看是否可以使用通知让它工作。 因此,如果我能得到任何帮助那就太好了。
最佳答案
已读取的数据将传递到 userInfo
字典中 NSFileHandleNotificationDataItem
键下的通知,您应该访问该通知而不是尝试读取更多数据。例如。像这样:
- (void) output:(NSNotification *)notification
{
NSString *output = [[NSString alloc]
initWithData:notification.userInfo[NSFileHandleNotificationDataItem]
encoding:NSUTF8StringEncoding];
NSLog(@"output: '%@'", output);
}
HTH
关于objective-c - echo 不适用于 NSTask 和 readInBackgroundAndNotify,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27511594/