2012-09-03 67 views
0

我正在開發一個應用程序使用UITabBarController。更具體地說,使用storyBoard。我希望我的所有標籤都能夠從服務器發送和接收數據。在tabBarView管理套接字流

問題是我不知道如何。只有具有initNetworkCommunications的第一個選項卡才能夠從服務器發送和接收數據。那麼,爲了讓我的應用能夠發送和接收其他選項卡,我該怎麼做?

我發現使用NSNotificationCentre來處理數據會工作,但有另一種方式嗎?

下面是創建套接字連接的代碼

-(void)initNetworkCommunication 
{ 
CFReadStreamRef readStream; 
CFWriteStreamRef writeStream; 
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"169.254.1.1", 2000, &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]; 

} 

可以說我有2個選項卡。第一個標籤有一個連接按鈕,用於調用initNetworkCommunication。從這個標籤我能夠發送和接收數據。但是,我如何處理另一個標籤?有沒有辦法鏈接這個連接?

我試着導入對方的控制器並使用[FirstController sendMessage];來自secondViewController但似乎不起作用。

回答

0

最簡單的方法是創建一個Singleton,我們稱它爲NetworkCommunications。

爲了讓辛格爾頓(只有一個實例將被創建):

+(NetworkCommunications *)sharedManager { 
    static dispatch_once_t pred; 
    static NetworkCommunications *shared = nil; 

    dispatch_once(&pred, ^{ 
     shared = [[NetworkCommunications alloc] init]; 
    }); 
    return shared; 
} 

然後你只需要調用[NetworkCommunications sharedManager]從您的選項卡,以訪問該單個實例。

你也把你的網絡代碼放在那個實例中。

+0

你是什麼意思你把你的網絡代碼在那個實例呢? – user1634769

+0

把所有與網絡相關的方法,如initNetworkCommunication。 – Resh32

2

創建一個singleton很好,我所做的就是不用創建一個類函數(這將迫使你的網絡在每次切換標籤頁時重新初始化連接)我使用networkconnector作爲自定義實現的一個屬性的TabBar的:

#import <Foundation/Foundation.h> 
#import "NetworkController.h" 

@interface NetworkStorageTabBarController : UITabBarController 
@property (nonatomic, strong) NetworkController *thisNetworkController; 
@end 

和實現文件:

#import "NetworkStorageTabBarController.h" 

@implementation NetworkStorageTabBarController 
@synthesize thisNetworkController; 
@end 

後來,當我打開了我的標籤視圖,我稱這種現象爲第一視圖的viewWillAppear中會出現:

//set up networking 
NetworkStorageTabBarController *thisTabBar = (NetworkStorageTabBarController *) self.tabBarController; 
self.thisNetworkController = thisTabBar.thisNetworkController; 
self.thisNetworkController.delegate = self; 

到目前爲止,這對我來說是光榮的。讓我永遠把它弄清楚,所以我希望這有助於!