Store userid in memory IOS

一个人想着一个人 提交于 2019-12-02 08:59:24
Giuseppe Andrea Mosca

You can store userId in the AppDelegate.


Declare a userId property in AppDelegate.h with the following code:

@property (nonatomic, strong) NSString *userId

And then synthesize it in AppDelegate.m with the following code:

@synthesize userId;

You can then use userId from anywhere in your app. Add an import for the AppDelegate in the class you want to use userId, as follows:

#import "AppDelegate.h"

To retrieve the userId use the following code:

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *userId = [appDelegate userId];

And to set the userId use the following code:

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[appDelegate setUserId:YouValueRetrievedByInternetOrWhateverYouWant];

Have a session class that works as a singleton and can be accessed with a static method.

To do this you can add a static method

+ (Session *)sharedInstace {
    static Session *session;
    if (!session)
        session = [Session new]; // there are more proper ways to instantiate a singleton class, not gonna get into it now

    return session.
}

On that class .h you should add a NSString (or a class of your choice or whatever you want) and you can access it from wherever with [Session sharedInstance].userID

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!