objective c singleton return nil

时间:2017-02-07 03:10:04

标签: objective-c xcode singleton

我有单例使用websocket连接,当_srWebSocket = nil时,会返回新的_srWebSocket,但是当_srWebSocket连接时,会返回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;

2 个答案:

答案 0 :(得分:1)

您缺少srWebSocket方法调用,

第一种方式,

在singleton.h文件中声明一个方法

-(void) doInitialSetupOnLaunch;

在singleton.m文件中的某处添加此方法,

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

 _srWebSocket = [self srWebSocket];
}

- (SRWebSocket *) srWebSocket {
    if (!_srWebSocket || _srWebSocket.readyState == SR_CLOSED) {
        _srWebSocket = [[SRWebSocket alloc] initWithURL:[NSURL URLWithString:@"wss://...:8000"]];
        [_srWebSocket open];
    }
    return _srWebSocket;
}

从某处调用它,最好的方法是从appDelegate.m

调用

现在您已准备好按属性

访问它
Call singleton 
srWebSocket = [SocketManager sharedInstance].srWebSocket;

或第二种方式

SRWebSocket * srWebSocket = [[SocketManager sharedInstance] srWebSocket]; 

答案 1 :(得分:1)

因为你写了'static SocketManager * sharedInstance = nil;'在shareInstance方法中。 当这个方法每次发送nil时调用。

 + (SocketManager *) sharedInstance {
static SocketManager *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    sharedInstance = [[SocketManager alloc] init];
});
return sharedInstance;

}

在shareInstance方法之外写下这一行“static SocketManager * sharedInstance = nil;”