我在单例类中保留了一个套接字,如下所示:
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控制台日志中没有任何内容。请帮忙看看为什么它不能调用委托方法?
答案 0 :(得分:0)
您正在使用SocketConnection的getInstance
方法初始化套接字,此时您将委托设置为self
。 self
指的是SocketConnection实例,而不是您的视图控制器。在视图控制器中初始化套接字(此时它不再是单例),或者在SocketConnection上创建委托属性并将委托方法传递给SocketConnection的委托。就个人而言,我是后者,但是我发出通知而不是委托消息。