我已经在一个单独的类IBStore中分隔了我的网络代码。代码非常简单,并且基于提供的示例:
#import <UIKit/UIKit.h>
#import "GCDAsyncSocket.h"
@interface IBStore : UIViewController
{
GCDAsyncSocket *socket;
}
- (void)connect;
- (void)socket:(GCDAsyncSocket *)sender didConnectToHost:(NSString *)host port:(UInt16)port;
- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag;
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag;
@end和:
#import "IBStore.h"
@interface IBStore ()
@end
@implementation IBStore
- (void)connect
{
socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSError *err = nil;
if (![socket connectToHost:@"127.0.0.1" onPort:80 error:&err]) // Asynchronous!
{
// If there was an error, it's likely something like "already connected" or "no delegate set"
NSLog(@"Connection error: %@", err);
}
}下面是从主视图控制器实例化IBStore的方式:
- (IBAction)connect:(id)sender {
IBStore *client = [[IBStore alloc]init];
[client connect];
}不幸的是,在执行socket4FD = socket(AF_INET, SOCK_STREAM, 0);时,GCDAsyncSocket.m中的应用程序不是执行didConnectToHost,而是崩溃(挂起
任何关于为什么会发生这种情况的想法都将受到高度赞赏。谢谢!
发布于 2012-06-11 23:11:21
我的错误是在connect方法中声明和实例化IBStore类。现在,我已经将IBStore *client声明为实例变量,它可以完美地工作。
https://stackoverflow.com/questions/10955269
复制相似问题