Qwerty Qwerty - 4 years ago 224
Objective-C Question

objective c singleton return nil

I have singleton to use websocket connection, when _srWebSocket = nil, will returned new _srWebSocket, but when _srWebSocket connected, will returned nil

@interface SocketManager : NSObject

@property (nonatomic, weak) SRWebSocket *srWebSocket;

+ (SocketManager *) sharedInstance;

@end

@implementation SocketManager

@synthesize srWebSocket = _srWebSocket;

+ (SocketManager *) sharedInstance {
static SocketManager *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[SocketManager alloc] init];
});
return sharedInstance;
}
- (id)init {
if (self = [super init]) {
NSLog(@"In SocketKeeperSingleton init");
}
return self;
}
- (SRWebSocket *) srWebSocket {
if (!_srWebSocket || _srWebSocket.readyState == SR_CLOSED) {
_srWebSocket = [[SRWebSocket alloc] initWithURL:[NSURL URLWithString:@"wss://...:8000"]];
[_srWebSocket open];
}
return _srWebSocket;
}

@end
Call singleton
srWebSocket = [SocketManager sharedInstance].srWebSocket;

Answer Source

You are missing srWebSocket method call,

First way,

Declare one method in singleton.h file

-(void) doInitialSetupOnLaunch;

Add this method somewhere in your singleton.m file,

-(void) doInitialSetupOnLaunch {
   //Put your initialized code i mean you can call your method from here & define your properties here.

 _srWebSocket = [self srWebSocket];
}

Call it from somewhere,best way you can call from appDelegate.m

Now you are ready to access it by property,

Call singleton 
srWebSocket = [SocketManager sharedInstance].srWebSocket;

Or Second way

SRWebSocket * srWebSocket = [[SocketManager sharedInstance] srWebSocket]; 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download