views:

37

answers:

2

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 project. 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?

A: 

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:...];
JosephH
One really should avoid global state, so this is not a good idea. There is a reason why this isn’t done very often.
Sven
That was my intention, but I guess I didn't convey it well - I've reordered/reworded my answer to make that clearer.
JosephH
+1  A: 

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];
Sedate Alien