2013-06-19 49 views
1

我從app開始連接到服務器的appdelegate中設置套接字連接。 在appdelegate.h如何從appdelegate共享NSOutputStream?

@interface AppDelegate : NSObject <NSStreamDelegate,UIApplicationDelegate> { 
    UIWindow *window; 
    UITabBarController *tabBarController; 
    NSInputStream *inputStream; 
NSOutputStream *outputStream; 
} 

然後在appdelegate.m設置連接到服務器:

 CFReadStreamRef readStream; 
CFWriteStreamRef writeStream; 
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"111.111.111.11", 111, &readStream, &writeStream); 

inputStream = (NSInputStream *)readStream; 
outputStream = (NSOutputStream *)writeStream; 
[inputStream setDelegate:self]; 
[outputStream setDelegate:self]; 
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; 
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; 
[inputStream open]; 
[outputStream open]; 

它運行良好時,應用程序啓動時。溝通也很好。

然後我有一個選項卡控制器。每個選項卡都需要通過此套接字將數據交換到服務器。我不想爲每個選項卡創建不同的套接字。

如何使用相同的outputstream/inputstream?

我嘗試這firstviewcontroall.m但失敗:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    NSData *data = [[NSData alloc] initWithData:[@"hello this is firstview" dataUsingEncoding:NSUTF8StringEncoding]]; 
[outputStream write:[data bytes] maxLength:[data length]]; 
} 

沒有DATAS發送給服務器。我不想在每個視圖控制器上創建一個套接字到服務器。這浪費了太多資源。我的問題是如何通過一個套接字連接發送/接收數據?

回答

2

通過以下方式使用流:

AppDelegate *appDel = (AppDelegate *)[UIApplication sharedApplication].delegate; 
[appDel.outputStream write:[data bytes] maxLength:[data length]]; 
[appDel.inputStream <CALL_YOUR_METHOD>]; 
+0

是的,謝謝,輸出流正在工作。但我無法使輸入流工作。輸入流在appdelegate.m中正常工作,但firstviewcontroller.m。 – STANLEY

+0

@STANLEY:請參閱最新的答案。 – Apurv

+0

它顯示警告「NSInputstream可能不響應'方法'」。有一種方法已經在appdelegate.m中響應inputstream。我猜這兩個方法是彼此交錯的。有沒有辦法將appdelegate.m中的變量傳遞給fristviewcontrol.m,然後激活另一種方法來執行其他操作? – STANLEY

1

我會創建一個實用程序/管理器類來處理與服務器的通信。通過這種方式,您可以輕鬆訪問代碼的其他部分。也很容易確保它是線程安全的。請注意,您應該考慮不在主線程中執行這些操作。

然而,這裏是,如果你想訪問的AppDelegate定義的變量代碼:

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; 
[appDelegate.outputStream <method>]; 
+0

如果我創建一個類處理這與服務器,我必須在每個選項卡上建立連接嗎?如果沒有,我會回到這個問題。我猜他們應該是類似的東西。 – STANLEY

+0

有多種方式可以共享訪問對象。檢查以下鏈接以瞭解如何使您的對象成爲單身人士並從不同的選項卡/類共享:http://stackoverflow.com/questions/145154/what-should-my-objective-c-singleton-look-like – rakmoh