将用户输入的主机添加到套接字,同时对套接字使用单例



我正在使用单例来创建全局套接字。当应用启动时,系统会提示用户输入代码,该代码将用于连接到主机套接字。如何将数据字符串从视图控制器传递到要用作 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]

最新更新