0

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

套接字连接.h

@interface SocketConnection : NSObject

+ (GCDAsyncSocket *) getInstance;

@end

套接字连接.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

在视图控制器中:

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

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

4

1 回答 1

0

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

于 2012-10-09T02:46:04.370 回答