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

后端 未结 3 1528
执笔经年
执笔经年 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:26

    The following code using NSString instead of numbers and setting a local variable rather than a property works:

    Session.h
    @interface IDSession : NSObject
    @property (readonly, copy) NSString *userid;
    + (IDSession *)sharedInstance;  
    @end
    
    Session.m
    #import "IDSession.h"
    @interface IDSession()
    @property (readwrite,copy)NSString * userid;
    
    @end
    
    @implementation IDSession
    
    + (IDSession *)sharedInstance {
        static IDSession *session;
        if (!session){
            session = [[IDSession alloc] init];
            //include this class in other class and reference userid with [IDSession sharedInstance].userid
            NSString * userid = @"1";
        }
        return session;
    }
    @end
    in retrieving class.
    
    #import "session.h"
    
       NSString *userid =[Session sharedInstance].userid;
        NSLog(@"userid retrieved from session variable is %@",userid);
    

提交回复
热议问题