[英]Objective-C: Multiple Views and Data Coming From An NSTask
因此,我設法使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上使用。 謝謝。
快速的方法是
在所有您希望收到相同通知的視圖中,添加以下內容
ReceiverView
-(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]
}
請注意,new_input已分配但未釋放=>內存泄漏
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.