0

在发布类似问题(不起作用)之后,我在 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

4

1 回答 1

2

你在正确的轨道上。应用程序委托是套接字连接的好地方。我认为你被一些相对简单的事情绊倒了。

[[UIApplication sharedApplication] delegate]返回一个id或通用对象指针,指向符合<UIApplicationDelegate>协议的对象。因此代码完成无法知道您的应用程序的委托是您的 AppDelegate类的实例。

请记住,如果您实际上使用 的实例作为AppDelegate应用程序的委托,那么[[UIApplication sharedApplication] delegate]将返回一个指向您的委托的指针,但它将是上面讨论的通用指针。

最简单的解决方案是将收到[[UIApplication sharedApplication] delegate]的指针转换为AppDelegate类型指针。

例如:

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
// We now have a pointer to your app delegate that the compiler knows is an AppDelegate.
// So code completion will work and it will compile.
GCDAsyncSocket *socket = [myAppDelegate asyncSocket];

或者,您可以将调用堆叠到一个语句。语法看起来有点古怪,但这就是它的完成方式。

GCDAsyncSocket *socket = [(AppDelegate *)[[UIApplication sharedApplication] delegate] asyncSocket];
于 2012-08-30T17:03:08.567 回答