简体   繁体   中英

singleton in ios with user defaults

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.

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 .

+(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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM