Store userid in memory IOS

 ̄綄美尐妖づ 提交于 2019-12-31 07:17:32

问题


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



来源:https://stackoverflow.com/questions/13705093/store-userid-in-memory-ios

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