将用户标识存储在内存 IOS 中



我做了一个带有登录功能的IOS应用程序。我为此使用 ASIHTTPRequest 来检查用户是否存在于 MySQL 数据库中。一切正常,但我想通过其他视图控制器传递 userid 或在应用程序的其他部分检索它。

有人可以推动我朝着正确的方向前进,如何以最好和最安全的方式做到这一点吗?

这是我对PHP脚本执行POST HTTP请求的方式:

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

在回调中,我可以检索用户 ID,但我想将此 ID 存储在应用程序的内存中以供进一步使用。

谢谢。

您可以将userId存储在AppDelegate中。


使用以下代码在 AppDelegate.h 中声明 userId 属性:

@property (nonatomic, strong) NSString *userId

然后使用以下代码以AppDelegate.m合成它:

@synthesize userId;

然后,您可以在应用中的任何位置使用userId。 为要使用的类中的AppDelegate添加导入 userId ,如下所示:

#import "AppDelegate.h"

若要检索userId请使用以下代码:

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

要设置userId使用以下代码:

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

有一个会话类,该会话类用作单一实例,可以使用静态方法访问。

为此,您可以添加一个静态方法

+ (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.
}

在该类.h上,您应该添加一个NSString(或您选择的类或任何您想要的类),并且您可以使用[Session sharedInstance].userID从任何地方访问它

最新更新