因此,我设法让 NSTask 从程序中异步读取,但我是在 Storyboard 中的 UIView 类中完成的。 (不是 Obj-C 专家)
我的想法是:我从程序中读取文本,将其放在 UITextView 上,然后当有更多文本时,通过 NSNotificationCenter
重复该过程
到目前为止,这是我的代码:
LView.m:
- (void)viewDidLoad
{
[super viewDidLoad];
NSPipe *out_pipe = [NSPipe pipe];
sshoutput = [out_pipe fileHandleForReading];
[sshoutput readInBackgroundAndNotify];
utilT = [[NSTask alloc] init];
[utilT setLaunchPath:@"/usr/bin/utilfc9"];
[utilT setArguments:[NSArray arrayWithObjects: @"-p", @"-f", @"log.txt", nil]];
[utilT setStandardOutput: out_pipe];
[utilT setStandardError: out_pipe];
[utilT launch];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(readPipe:) name:NSFileHandleReadCompletionNotification object:nil];
}
-(void)readPipe: (NSNotification *)notification
{
NSData *data;
NSString *new_input;
if( [notification object] != sshoutput ) { return };
data = [[notification userInfo] objectForKey:NSFileHandleNotificationDataItem];
new_input = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
self.log.text = [self.wifilog.text stringByAppendingFormat: @"\n%@", new_input];
if( utilT ) {
[sshoutput readInBackgroundAndNotify];
}
}
LView.h:
#import <UIKit/UIKit.h>
#import "NSTask.h"
NSTask *sshT;
NSFileHandle *sshoutput;
到目前为止,效果很好,我可以正常获取数据。
但是,我怎样才能把这个 NSTask 放在一个更“全局”的地方,比如 AppDelegate 的 application didFinishLaunchingWithOptions ,然后处理数据并更新另一个类中的多个 View ?我尝试过,当然我可以在 AppDelegate 中添加类似 log.text = new_input
的内容,因为它来自另一个类,并且包含它并不能解决问题。
正如您可能注意到的,我对将其发送到 AppStore 不感兴趣。这是我自己在越狱的 iPhone 上使用的应用程序。 谢谢。
最佳答案
快速的方法是
在您想要接收同一通知的所有 View 中添加以下内容
接收者 View
-(void) viewDidLoad
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(read:) name:@"ReadTest" object:nil];
}
//read function
-(void) read:(NSNotification*)notification
{ // Do something with the notification }
现在在 LView.m
-(void)readPipe: (NSNotification *)notification
{
NSData *data;
NSString *new_input;
if( [notification object] != sshoutput ) { return };
data = [[notification userInfo] objectForKey:NSFileHandleNotificationDataItem];
new_input = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
self.log.text = [self.wifilog.text stringByAppendingFormat: @"\n%@", new_input];
if( utilT ) {
[sshoutput readInBackgroundAndNotify];
}
//Add the following
[[NSNotificationCenter defaultCenter] postNotificationName:@"ReadTest" object:notification]
}
关于Objective-C:来自 NSTask 的多个 View 和数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10865220/