如何使AppDelegate中声明的GCDAsyncSocket可用于查看控制器

时间:2012-08-28 02:24:28

标签: xcode ios5 gcdasyncsocket appdelegate

发布类似问题的帖子(不起作用)后,我在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]委托]处停止,而无法建议asyncSocket。 在AppDelegate中声明asyncSocket实例时,如何在多个视图控制器中访问asyncSocket?谢谢!

这是我的Xcode项目文件:http://bit.ly/PLe1Le

1 个答案:

答案 0 :(得分: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];