【发布时间】:2012-06-02 19:21:37
【问题描述】:
所以,我设法让 NSTask 从程序中异步读取,但我是在故事板中的 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 这样更“全局”的地方,然后处理数据并更新另一个类中的多个视图?我试过了,当然我可以在 AppDelegate 中添加log.text = new_input 之类的东西,因为它来自另一个类,包含它并不能解决问题。
您可能已经注意到,我对将其发送到 AppStore 不感兴趣。这是一个供我自己在越狱的 iPhone 上使用的应用程序。 谢谢。
【问题讨论】:
标签: objective-c ios nsnotificationcenter nstask