开发者

How to declare AsyncSocket instance as Global

I am using AsyncSocket class for a chat application. But i want to use the AsyncSocket instance creating in the Login page for the entire p开发者_JAVA百科roject. That means i want to reuse the instance of AsyncSocket which created in the Login page for the chatViewControl Class. Can anyone help me to find a solution for this?


If you wish to have an application-wide reference to a single AsyncSocket, you could consider declaring it as a property of your application delegate. You could do it along the following lines:

// SampleAppDelegate.h
#import <Foundation/Foundation.h>

@class AsyncSocket;

@interface SampleAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;
    AsyncSocket *socket;
}

@property (nonatomic,retain) AsyncSocket *socket;

// SampleAppDelegate.m
#import <SampleAppDelegate.h>
#import <AsyncSocket.h>

@implementation SampleAppDelegate

@synthesize socket;

- (void)applicationDidFinishLaunching:(UIApplication *)application
{
    [window addSubview:[splitViewController view]];
    [window makeKeyAndVisible];
    self.socket = [[AsyncSocket alloc] init]; // I can't remember this off the top of my head!
}

From this point on you can access your socket by simply doing:

AsyncSocket *socket = [UIApplication sharedApplication] delegate] socket];


You should really avoid global state where possible (see Sven's link). In general you're probably better of having some kind of object that you pass around to your other objects.

For example, the current app I'm working on I have a ServerInfo object that I create before logging in and pass to each new view controller when I create it, and it contains the socket, encryption information, current message id, username, etc.

However, to answer the question of how to declare it as a global, you can do it just like in C:

in login.h:

extern AsyncSocket *g_socket;

in login.m:

AsyncSocket *g_socket;

then when you create the socket:

g_socket = [[AsyncSocket alloc] init];

and when you want to use it in other files:

#import "login.h"

...

[g_socket sendData:...];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜