将用户输入的主机添加到套接字,同时为套接字使用单例
Adding a user inputted host to a socket, while using a singleton for the socket
我正在使用单例创建全局套接字。
当应用程序启动时,系统会提示用户输入代码,该代码将用于连接到主机套接字。我如何将数据字符串从视图控制器传递到单例中以用作 URL。这就是我设置单身人士的方式。
+ (SocketKeeperSingleton *) sharedInstance {
static dispatch_once_t _once;
static SocketKeeperSingleton *sharedSingleton = nil;
dispatch_once(&_once, ^{
sharedSingleton = [[SocketKeeperSingleton alloc] init];
[sharedSingleton initSIOSocket];
});
return sharedSingleton;
}
-(void) initSIOSocket {
[SIOSocket socketWithHost:@"http://localhost:8080" response:^(SIOSocket *socket) {
self.socket = socket;
[self.socket on:@"q_update_B" callback:^(NSArray *args) {
NSArray *tracks = [args objectAtIndex:0];
self.setListTracks = tracks;
[[NSNotificationCenter defaultCenter] postNotificationName:@"qUpdateB" object:nil];
}];
[self.socket on:@"current_artist_B" callback:^(NSArray *args) {
self.currentArtist = [args objectAtIndex:0];
[[NSNotificationCenter defaultCenter] postNotificationName:@"currentArtistB" object:nil];
}];
}];
}
你可以简单地将你的单例重构为这样的东西
+ (SocketKeeperSingleton *)sharedInstance {
static dispatch_once_t _once;
static SocketKeeperSingleton *sharedSingleton = nil;
dispatch_once(&_once, ^{
sharedSingleton = [[SocketKeeperSingleton alloc] init];
});
return sharedSingleton;
}
- (void)startSIOSocketWithHost:(NSString *)sHost {
[SIOSocket socketWithHost:sHost response:^(SIOSocket *socket) {
...
然后用户输入后的第一个单例用法可以是 [[SocketKeeperSingleton sharedInstance] startSIOSocketWithHost:userInput]
我正在使用单例创建全局套接字。 当应用程序启动时,系统会提示用户输入代码,该代码将用于连接到主机套接字。我如何将数据字符串从视图控制器传递到单例中以用作 URL。这就是我设置单身人士的方式。
+ (SocketKeeperSingleton *) sharedInstance {
static dispatch_once_t _once;
static SocketKeeperSingleton *sharedSingleton = nil;
dispatch_once(&_once, ^{
sharedSingleton = [[SocketKeeperSingleton alloc] init];
[sharedSingleton initSIOSocket];
});
return sharedSingleton;
}
-(void) initSIOSocket {
[SIOSocket socketWithHost:@"http://localhost:8080" response:^(SIOSocket *socket) {
self.socket = socket;
[self.socket on:@"q_update_B" callback:^(NSArray *args) {
NSArray *tracks = [args objectAtIndex:0];
self.setListTracks = tracks;
[[NSNotificationCenter defaultCenter] postNotificationName:@"qUpdateB" object:nil];
}];
[self.socket on:@"current_artist_B" callback:^(NSArray *args) {
self.currentArtist = [args objectAtIndex:0];
[[NSNotificationCenter defaultCenter] postNotificationName:@"currentArtistB" object:nil];
}];
}];
}
你可以简单地将你的单例重构为这样的东西
+ (SocketKeeperSingleton *)sharedInstance {
static dispatch_once_t _once;
static SocketKeeperSingleton *sharedSingleton = nil;
dispatch_once(&_once, ^{
sharedSingleton = [[SocketKeeperSingleton alloc] init];
});
return sharedSingleton;
}
- (void)startSIOSocketWithHost:(NSString *)sHost {
[SIOSocket socketWithHost:sHost response:^(SIOSocket *socket) {
...
然后用户输入后的第一个单例用法可以是 [[SocketKeeperSingleton sharedInstance] startSIOSocketWithHost:userInput]