【问题标题】:AsyncSocket delegate method not called未调用 AsyncSocket 委托方法
【发布时间】:2012-10-09 02:38:32
【问题描述】:

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

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 控制台日志中没有任何内容。请帮忙看看为什么它不能调用委托方法?

【问题讨论】:

    标签: ios cocoaasyncsocket


    【解决方案1】:

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

    【讨论】:

    • 谢谢。我更喜欢发送通知。我的单身班级会很大吗,因为它会收到每个通知。您的意思是像下面这样在我的单例类中添加观察者吗? [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(login) name:@"event_login" object:nil];
    • 我想明白了。我应该向不同的班级发送不同的通知。
    • 是的,您不会在单例中观察通知,而是发布它们。订阅这些通知的任何人(通常是您的活动视图控制器)都会收到通知。
    • 嘿@Scott,另一个问题。我将所有套接字委托方法移动到我的套接字单例中,并在 viewController 中使用[[SocketConnection getInstance] writeData:data withTimeout:-1 tag:-1] 发送数据,但无法调用委托方法。有什么问题吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-12
    • 1970-01-01
    相关资源
    最近更新 更多