2012-10-09 56 views
0

我保留一个单独的类插座像以下:AsyncSocket委托方法

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

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

+0

谢谢。我更愿意发送通知。我的单身人士课程会非常大,因为它会收到每一个通知。你的意思是在我的单身类像下面的addObserver? '[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(login)name:@“event_login”object:nil];' – goofansu

+0

我认为重点。我应该派遣不同的通知给不同的班级。 – goofansu

+0

是的,你没有观察到你的单身通知,你发布它们。那些订阅(通常是您的活动视图控制器)这些通知的任何人都会收到通知。 –