我在单例类中保留了一个套接字,如下所示:
套接字连接.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 控制台日志中没有任何内容。请帮忙看看为什么它不能调用委托方法?