Ios 未调用AsyncSocket委托方法

Ios 未调用AsyncSocket委托方法,ios,cocoaasyncsocket,Ios,Cocoaasyncsocket,我在singleton类中保留一个套接字,如下所示: SocketConnection.h @interface SocketConnection : NSObject + (GCDAsyncSocket *) getInstance; @end SocketConnection.m #define LOCAL_CONNECTION 1 #if LOCAL_CONNECTION #define HOST @"localhost" #define PORT 5678 #else #defi

我在singleton类中保留一个套接字,如下所示:

SocketConnection.h

@interface SocketConnection : NSObject

+ (GCDAsyncSocket *) getInstance;

@end
SocketConnection.m

#define LOCAL_CONNECTION 1

#if LOCAL_CONNECTION
#define HOST @"localhost"
#define PORT 5678
#else
#define HOST @"foo.abc"
#define PORT 5678
#endif

static GCDAsyncSocket *socket;

@implementation SocketConnection

+ (GCDAsyncSocket *)getInstance
{
    @synchronized(self) {
        if (socket == nil) {
            dispatch_queue_t mainQueue = dispatch_get_main_queue();
            socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:mainQueue];
        }
        if (![socket isConnected]) {

            NSString *host = HOST;
            uint16_t port = PORT;
            NSError *error = nil;

            if (![socket connectToHost:host onPort:port error:&error])
            {
                NSLog(@"Error connecting: %@", error);
            }
        }
    }

    return socket;
}

- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
    NSLog(@"socket connected");
}

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
    NSLog(@"socketDidDisconnect:%p withError: %@", sock, err);
}

@end
在viewController中:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _socket = [SocketConnection getInstance];
    }
    return self;
}

我可以看到套接字已连接到我的服务器中,但我的xcode控制台日志中没有任何内容。请帮助查看它为什么无法调用委托方法?

您正在SocketConnection的
getInstance
方法中初始化套接字,此时您将委托设置为
self
self
指的是SocketConnection实例,而不是视图控制器。在视图控制器中初始化套接字(此时它不再是单例),或者在SocketConnection上创建一个委托属性,并将委托方法传递给SocketConnection的委托。就个人而言,我会做后者,但我会发送通知,而不是代表信息。

谢谢。我更喜欢发送通知。我的singleton类将非常大,因为它将收到每个通知。你是说像下面这样在我的单人课上加入观察者吗<代码>[[NSNotificationCenter defaultCenter]添加观察者:自选择器:@selector(login)name:@“event_login”对象:nil]我想我明白了。我应该向不同的类发送不同的通知。是的,你在你的单例中没有观察到通知,而是发布它们。任何订阅(通常是您的活动视图控制器)这些通知的人都将收到通知。嘿@Scott,另一个问题。我将所有套接字委托方法移动到我的套接字单例,并在viewController中使用
[[SocketConnection getInstance]writeData:data withTimeout:-1标记:-1]
发送数据,但无法调用委托方法。有什么不对劲吗?