【问题标题】:Store userid in memory IOS将用户ID存储在内存IOS中
【发布时间】:2012-12-04 14:25:06
【问题描述】:

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

有人能把我推向正确的方向吗?如何以最好和最安全的方式做到这一点?

这是我向 PHP 脚本发出 POST HTTP 请求的方式:

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

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

谢谢。

【问题讨论】:

  • 呃……MySQL 并不完全……在 iOS 上工作。核心数据包装 SQLite。此外,也许您可​​以向我们展示您目前所拥有的东西,这样不仅仅是您需要代码。
  • 您希望将密码和登录信息保留多长时间? ASIHTTPRequest 允许在钥匙串中保存凭据(将“useKeychainPersistence”设置为 YES ),因此可以使用静态方法(+ (NSURLCredential *)savedCredentialsForHost:(NSString *)host port:(int)port protocol:( NSString *)协议领域:(NSString *)realm;)
  • 感谢您的留言,我不想存储用户名和密码,只存储带有 UserID 的响应。

标签: ios xcode asihttprequest


【解决方案1】:

您可以将userId 存储在AppDelegate 中。


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

@property (nonatomic, strong) NSString *userId

然后在AppDelegate.m中合成,代码如下:

@synthesize userId;

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

#import "AppDelegate.h"

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

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

要设置userId,请使用以下代码:

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

【讨论】:

    【解决方案2】:

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

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

    + (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 从任何地方访问它

    【讨论】:

    • 嗨,这看起来很复杂,可能比存储在委托中更安全?感谢您的回答。得到了我需要的东西。
    • 存储一个变量不是问题,但根据我在同一个应用程序上工作多年的经验,您的 AppDelegate 可能会开始变得拥挤,您需要寻找其他选项:) 这不是真的复杂,您不需要到处进行繁重的应用程序委托转换,并且您将应用程序委托留给它管理应用程序事件的真正功能。
    • 为了未来读者的利益,如果你要实现单例模式,我可能会建议dispatch_once:galloway.me.uk/tutorials/singleton-classes
    猜你喜欢
    • 1970-01-01
    • 2011-10-14
    • 1970-01-01
    • 1970-01-01
    • 2014-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-09
    相关资源
    最近更新 更多