在发布类似问题(不起作用)之后,我在 AppDelegate.h 上声明了一个 GCDAsyncSocket 实例
#import <UIKit/UIKit.h>
@class ViewController;
@class GCDAsyncSocket;
@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
GCDAsyncSocket *asyncSocket;
}
@property (strong, nonatomic) UIWindow *window;
@property (nonatomic, retain) GCDAsyncSocket *asyncSocket;
@property (strong, nonatomic) ViewController *viewController;
@end
并在 AppDelegate.m 中进行套接字初始化
#import "AppDelegate.h"
#import "GCDAsyncSocket.h"
#import "ViewController.h"
@implementation AppDelegate
@synthesize asyncSocket;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
dispatch_queue_t mainQueue = dispatch_get_main_queue();
self.asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:mainQueue];
NSString *host = @"10.1.100.50";
uint16_t port = 3040;
NSError *error = nil;
if (![self.asyncSocket connectToHost:host onPort:port error:&error])
{
NSLog(@"Error connecting: %@", error);
}
char bytes[] = "run";
NSData* requestData = [[NSData alloc] initWithBytes:bytes length:sizeof(bytes)];
[self.asyncSocket writeData:requestData withTimeout:-1 tag:0];
return YES;
}
我试图通过调用从多个视图控制器访问套接字:
GCDAsyncSocket *asyncSocket = [[[UIApplication sharedApplication] delegate] asyncSocket];
代码完成在 [[UIApplication sharedApplication] delegate] 处停止,无法建议 asyncSocket。当在 AppDelegate 中声明 asyncSocket 的实例时,我应该怎么做才能在多个视图控制器中访问 asyncSocket?谢谢!
这是我的 Xcode 项目文件:http ://bit.ly/PLe1Le