2012-08-28 57 views
0

按照類似的問題(不工作)的職務GCDAsyncSocket,我就AppDelegate.h我如何做是在AppDelegate中聲明可用來查看控制器

宣佈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

回答

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]; 
相關問題