[英]How to gradually retrieve data from NSTask?
我正在為命令行工具使用GUI(Cocoa),以使人們更容易使用它。 盡管它是GUI,但我想將輸出顯示到NSTextView。 問題在於輸出量很大,該工具執行的分析可能需要數小時/天。
通常,使用NSTask和NSPipe時,僅在任務完全完成(可能需要很長時間)后才顯示輸出。 我要做的是將輸出拆分並逐漸顯示(例如,每分鍾更新一次)。
到目前為止,我已經將數據處理放在單獨的線程中:
[NSThread detachNewThreadSelector:@selector(processData:) toTarget:self withObject:raxmlHandle];
- (void)processData:(id)sender {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *startString = [results string];
NSString *newString = [[NSString alloc] initWithData:[raxmlHandle readDataToEndOfFile] encoding:NSASCIIStringEncoding];
[results setString:[startString stringByAppendingString:newString]];
[startString release];
[newString release];
[pool release];
}
這一切對我來說仍然有些巫毒,我不確定如何應對這一挑戰。
您有什么建議或建議嗎?
謝謝!
您需要使用NSFileHandle
提供的通知。
首先,將您自己添加為NSFileHandleReadCompletionNotification
的觀察者
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(outputReceived:)
name:NSFileHandleReadCompletionNotification
object:nil];
然后,准備任務,調用管道的文件句柄的readInBackgrounAndNotify ,然后啟動任務。
NSTask*task=[[NSTask alloc] init];
[task setLaunchPath:...];
NSPipe*pipe=[NSPipe pipe];
[task setStandardOutput:pipe];
[task setStandardError:pipe];
// this causes the notification to be fired when the data is available
[[pipe fileHandleForReading] readInBackgroundAndNotify];
[task launch];
現在,要實際接收數據,您需要定義一個方法
-(void)outputReceived:(NSNotification*)notification{
NSFileHandle*fh=[notification object];
// it might be good to check that this file handle is the one you want to read
...
NSData*d=[[aNotification userInfo] objectForKey:@"NSFileHandleNotificationDataItem"];
... do something with data ...
}
您可能需要閱讀“ 通知編程主題”以了解發生了什么。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.