0

I have a class that holds data such as username and password. These values are set from a viewcontroller with a text field. This class has methods that use the username and password that the user inputted to carry out certain tasks. How do I write my program so that the user only has to put their username and password once to use the methods in this other class? This way worked by using NSUserdefaults, but I want the data to go away every time a new app session is started. Any way I can accomplish this? Thanks!

In your AppDelegate.m file:

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults removeObjectForKey:@"key1"];
    [defaults removeObjectForKey:@"key2"];
    [defaults removeObjectForKey:@"key3"];

    return YES;
}
user2200321
  • 325
  • 1
  • 4
  • 18
  • 1
    You could simply overwrite the values in `NSUserDefaults` in your `ApplicationDidLaunch` method with nil? That way you get session-level persistence but it'd be easy to change this in future if you needed to. Hopefully I understood your question correctly. – Graham Jun 02 '13 at 20:46
  • Thanks, this makes a lot of sense. Can you give a quick code example of how to overwrite it? – user2200321 Jun 03 '13 at 00:59
  • Never mind, got it. Updated my answer for future readers. – user2200321 Jun 03 '13 at 01:22

1 Answers1

2

In applicationWillTerminate in your app delegate set the NSUserDefault that you are storing the values in to nil.

[[NSUserDefaults standardUserDefaults]
 setObject:nil forKey:@"username"];
savner
  • 830
  • 6
  • 7
  • 1
    See discussion on http://stackoverflow.com/q/13386505/1445366 - this method may not always get called. You might want to cache the date, and invalidate on launch if the user has been out of your app for some amount of time. – Aaron Brager Jun 03 '13 at 01:28