Store userid in memory IOS

2019-03-05 23:28发布

问题:

I made an IOS Application with a login function. I use the ASIHTTPRequest for this to check if the user exists in a MySQL database. All works fine but i want to pass the userid trough other viewcontrollers or retrieve it on other parts of the app.

Can someone push me in the right direction how to do this in the best and most secure way?

This is my the way i do a POST HTTP request to a PHP script:

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:@"*SOME_URL*"]];

In a callback i can retrieve the users ID, but i want to store this ID in the memory of the app for further use.

Thanks.

回答1:

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];


回答2:

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