Pergunta

I am working on a mobile app that connects to my web server with a login system. I have created the user object that, after the first login, should save its token for the next app restart. I also need this user object to be a singleton so that I can access the same instance from everywhere in my app. This is what I came up with so far:

+(id)sharedManager {
    static SECTUser *sharedMyManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedMyManager = [[self alloc] init];
    });
    return sharedMyManager;
}

-(id)init{
    if (self = [super init]) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

        NSString *savedToken = [ defaults objectForKey: @"token" ];
        NSString *savedName = [ defaults objectForKey: @"name" ];

        if(savedToken && savedName){
            _token = savedToken;
            _name = savedName;
        }
    }
    return self;
}

the sharedManager is used to create the singleton, and the init should only load the values the first time and on the first instantiation.

Is this the correct way to achieve the wanted behavior? Is there any way I can check if this works properly?

Thanks in advance.

Foi útil?

Solução

There is a break in code over here. One can directly call init method by below way.

SECTUser *userInfo = [[SECTUser alloc] init];

You should not allow this method to run outside the class. To achieve it, give proper attribute to init method by below way.

- (id)init __attribute__((unavailable("init is unavailable")));

Please refer more over here.

Outras dicas

+(id)sharedManager {
    static SECTUser *sharedMyManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedMyManager = [[self alloc] init];
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        sharedMyManager.savedToken = [ defaults objectForKey: @"token" ];
        sharedMyManager.savedName = [ defaults objectForKey: @"name" ];
    });
    return sharedMyManager;
}

btw you better store your tokens in keychain

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top