Save User Details Throughout Session

Discussion in 'iOS Programming' started by donaghy, Sep 6, 2009.

  1. donaghy macrumors member

    Joined:
    Aug 6, 2009
    #1
    Hi all, I have a login form that will take the user's username and password. I want to store this and access it whenever i want when i go to another form. Id prefer not to pass it to each form and store as a declared property on each form. I thought it would be possible to create a class with a username and password property and read and write to this. I created an instance of this class and write the values to the properties but of course this will drop when i release the instance.

    What would be the best method to do this?

    cheers.
     
  2. dejo Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #2
    I would suggest the use of NSUserDefaults for this task.
     
  3. PhoneyDeveloper macrumors 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #3
    What you're asking about is called a singleton. The app delegate, for instance, is a singleton. So are things like NSFileManager, the UIApplication object, and others. Apple does have some description about how to write a singleton object in Objective-C.

    The way I would do this would be to create a class that has a couple class methods that return the name and password properties. Something like this

    Code:
    @interface MyUserCredentials : NSObject
    {
    }
    
    +(NSString*)username;
    +(NSString*)password;
    +(void)setUserName:(NSString*)username;
    +(void)setPassword:(NSString*)password;@end
    Because of how Obj-C works you need to store the strings as file scope statics.

    If you want to store the strings between runs of the app you should store them in the keychain.
     
  4. donaghy thread starter macrumors member

    Joined:
    Aug 6, 2009

Share This Page