ios/objective c/singleton: Storing userid in session variable

后端 未结 3 1516
执笔经年
执笔经年 2021-01-29 11:18

I defined an NSInteger in a singleton (for userid) and access it in another class. However, while I have managed to get rid of error messages so it builds, the app crashes when

3条回答
  •  隐瞒了意图╮
    2021-01-29 11:48

    Firstly, I recommend you follow this idiom for creating a thread safe singleton.

    + (Singleton *)sharedSettings{
    
        static Singleton *singleton;
        static dispatch_once_t onceToken;
    
        dispatch_once(&onceToken, ^{
    
            singleton = [[self alloc] initPrivate];
    
        });
    
        return singleton;
    
    }
    
    - (instancetype)initPrivate{
    
        self = [super init];
        if(!self) return nil;
    
    
        return self;
    
    }
    

    Also, NSInteger is not an object. It is a typedef for a primitive long. So remove the object pointer.

    typedef long NSInteger;

    You seem to be confusing NSInteger with the NSNumber wrapper. Take a look at the docs for NSNumber.

提交回复
热议问题