I have created a singleton class whose job is to create a tcp socket connection and keep it open infinitely while the application is running. I believe my singleton class looks as it’s supposed to (with help from other StackOverflow questions to get me there) but my problem is that I do not know WHEN or HOW to invoke my class object. I’m still pretty new to iOS development, so this is all pretty foreign to me.
- My app has multiple views
- I want to use my singleton class to create a tcp socket connection and keep the connection open at all times
- I do not know WHERE to call/invoke my singleton class object
- I do not know HOW to call/invoke my singleton class object
- I am using the SmallSockets library
Here are my class files:
SocketConnection.h
#import <Foundation/Foundation.h>
@interface SocketConnection : NSObject
{
}
+ (SocketConnection *)getInstance;
@end
SocketConnection.m
#import "SocketConnection.h"
#import "imports.h"
static SocketConnection *sharedInstance = nil;
@implementation SocketConnection
- (id)init
{
self = [super init];
if (self)
{
while(1)
{
Socket *socket;
int port = 11005;
NSString *host = @"199.5.83.63";
socket = [Socket socket];
@try
{
NSMutableData *data;
[socket connectToHostName:host port:port];
[socket readData:data];
// [socket writeString:@"Hello World!"];
// Connection was successful //
[socket retain]; // Must retain if want to use out of this action block.
}
@catch (NSException* exception)
{
NSString *errMsg = [NSString stringWithFormat:@"%@",[exception reason]];
NSLog(errMsg);
socket = nil;
}
}
}
return self;
}
+ (SocketConnection *)getInstance
{
@synchronized(self)
{
if (sharedInstance == nil)
{
sharedInstance = [[SocketConnection alloc] init];
}
}
return sharedInstance;
}
@end
To use this Singleton, and the connection associated with it, you could simply call the getInstance method to get a reference to the connection that your trying to use. You would effectively do this instead of the typical alloc/init process. You can use the getInstance method from each of your views, and they will all maintain the same connection as you are intending.
Also, because the way you create the Singleton, if you call alloc/init instead of getInstance, you WILL create a new connection instead of using the previous one.
An example of how you might do this to create a reference within a view would be:
Code similar to this would cause all of your views to use the same connection, but WOULD NOT create the connection until you had a view onscreen that is using the connection. To create the connection at application startup, add this same ‘getInstance’ to one of your appDelegate methods.
Also, because you are using a singleton, and this variable is never really released, you may want to consider adding methods to reinitialize, remove and generally manage the connection to the server.