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?
-
You really should avoid global state. Just pass the `AsyncSocket` instance to the other objects that need it. Read about dependency injection: http://en.wikipedia.org/wiki/Dependency_injection – Sven Sep 21 '10 at 14:15
2 Answers
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];

- 10,999
- 6
- 38
- 59
-
Tried your suggestion by putting the socket inside AppDelegate but when I tried to access from other view controllers, the socket method invocation doesn't come out --> [UIApplication sharedApplication] delegate] . I am using CocoaAsyncSocket : https://github.com/robbiehanson/CocoaAsyncSocket Any idea? – Scott Aug 28 '12 at 01:44
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:...];

- 37,173
- 19
- 130
- 154
-
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 Sep 21 '10 at 14:16
-
That was my intention, but I guess I didn't convey it well - I've reordered/reworded my answer to make that clearer. – JosephH Sep 22 '10 at 01:56