2013-11-28 53 views
2

我知道這個問題已經被多次詢問了。在視圖控制器之間通過socketIO連接

我使用Xcode的Socket.IO客戶端(https://github.com/pkyeck/socket.IO-objc)。問題是我需要在許多視圖控制器中使用socketIO連接。

在ViewControllerA(h文件)我有這樣的:

#import "SocketIO.h" 

@inteface ViewControllerA : UIViewController <SocketIODelegate> { 
    SocketIO *socketIO; 
} 

(.m文件):

- (void) viewDidLoad { 
    ... 
    [socketIO connectToHot:@"localhost" onPort:1234]; 
} 


而ViewControllerB爲聊天室做,我需要得到這個socketIO用於與服務器通信的對象。我是對的,我需要做這件事嗎?

1)在ViewControllerB使相同ViewControllerA

#import "SocketIO.h" 

@inteface ViewControllerA : UIViewController <SocketIODelegate> { 
    SocketIO *socketIO; 
} 

2)在ViewControllerA塞克之前做出這樣的:

#import "viewControllerB.h" 

... 

viewControllerB *viewControllerB = (viewControllerB *)[storyboard instantiateViewControllerWithIdentifier:@"viewControllerB"]; 
viewControllerB.socketIO = socketIO; 
[self pushViewController:viewControllerB animated:YES]; 

或者,也許有一些簡單的方法,從多視圖訪問數據控制器?

+0

創建單身人士怎麼樣? – Guferos

+0

單身?第一次聽,你能舉個例子嗎? – user2058653

回答

5

儘管有些人不喜歡單身人士,但我發現他們在這種類型的情況下非常有用,在這種情況下,沒有明顯的數據「擁有者」。單例是一個只能作爲一個實例存在的對象。它是通過一個靜態方法在單例類本身訪問:

SocketKeeperSingleton.h

@interface SocketKeeperSingleton : NSObject 

@property (nonatomic, strong) SocketIO *socketIO; 
+ (SocketKeeperSingleton *) sharedInstance; 

@end 

SocketKeeperSingleton.m

#import "SocketKeeperSingleton.h" 

@implementation SocketKeeperSingleton 

// The synthesize will automatically generate a getter and setter 
@synthesize socketIO = _socketIO; 

+ (SocketKeeperSingleton *)sharedInstance { 
    static SocketKeeperSingleton *sharedInstance = nil; 
    static dispatch_once_t onceToken; 

    dispatch_once(&onceToken, ^{ 
     sharedInstance = [[self alloc] init]; 
    }); 
    return sharedInstance; 
} 

- (id)init { 
    if (self = [super init]) { 
     NSLog(@"In SocketKeeperSingleton init"); 
    } 
    return self; 
} 

// Override the getter for your socket 
- (SocketIO *)socketIO { 
    if (!_socketIO || check-to-see-if-your-socket-has-been-disconnected-or-failed) { 
     _socketIO = code-to-create-and-connect-your-socket-goes-here 
    } 
    return _socketIO; 
} 

@end 

然後,得到隨時隨地的插座在你的項目中,像這樣的:

SocketIO *mySocketIO = [SocketKeeperSingleton sharedInstance].socketIO; 

祝你好運!

+0

謝謝!我沒有這段代碼的所有者,這是我想要的! – user2058653

相關問題