我知道这个问题已经被多次提出过了。
我将Socket.IO客户端用于Xcode(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)在seque之前的ViewControllerA中创建:
#import "viewControllerB.h"
...
viewControllerB *viewControllerB = (viewControllerB *)[storyboard instantiateViewControllerWithIdentifier:@"viewControllerB"];
viewControllerB.socketIO = socketIO;
[self pushViewController:viewControllerB animated:YES];
或许有一些简单的方法可以从许多视图控制器访问数据?
答案 0 :(得分:5)
尽管有些人不喜欢Singletons,但我发现它们在这些类型的情况下非常有用,其中没有明显的“所有者”的数据。 Singleton是一个只存在于一个实例中的对象。它可以通过singleton类本身的静态方法访问:
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;
祝你好运!