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控制檯日誌中沒有任何內容。請幫忙看看爲什麼它不能調用委託方法?
謝謝。我更願意發送通知。我的單身人士課程會非常大,因爲它會收到每一個通知。你的意思是在我的單身類像下面的addObserver? '[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(login)name:@「event_login」object:nil];' – goofansu
我認爲重點。我應該派遣不同的通知給不同的班級。 – goofansu
是的,你沒有觀察到你的單身通知,你發佈它們。那些訂閱(通常是您的活動視圖控制器)這些通知的任何人都會收到通知。 –