我在单例类中保留了一个套接字,如下所示:
SocketConnection.h
@interface SocketConnection : NSObject
+ (GCDAsyncSocket *) getInstance;
@endSocketConnection.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控制台日志中没有任何内容。请帮助理解为什么它不能调用委托方法?
发布于 2012-10-09 10:46:04
您正在初始化SocketConnection的getInstance方法中的套接字,此时您将委托设置为self。self指的是SocketConnection实例,而不是您的视图控制器。在视图控制器中初始化套接字(此时它不再是单例),或者在SocketConnection上创建委托属性并将委托方法传递给SocketConnection的委托。就我个人而言,我做的是后者,但我发送通知,而不是委托消息。
https://stackoverflow.com/questions/12792132
复制相似问题