首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >未调用AsyncSocket委托方法

未调用AsyncSocket委托方法
EN

Stack Overflow用户
提问于 2012-10-09 10:38:32
回答 1查看 987关注 0票数 0

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

SocketConnection.h

代码语言:javascript
复制
@interface SocketConnection : NSObject

+ (GCDAsyncSocket *) getInstance;

@end

SocketConnection.m

代码语言:javascript
复制
#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中:

代码语言:javascript
复制
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _socket = [SocketConnection getInstance];
    }
    return self;
}

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-10-09 10:46:04

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12792132

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档