views:

360

answers:

3

I want to check if my iPhone app is running for the first time. I can create a file in the documents folder and check that file to see if this is the first time the app is running, but I wanted to know if there is a better way to do this.

+6  A: 

I like to use NSUserDefaults to store an indication of the the first run.

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];  
if (![defaults objectForKey:@"firstRun"])
  [defaults setObject:[NSDate date] forKey:@"firstRun"];

[[NSUserDefaults standardUserDefaults] synchronize];

You can then test for it later...

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];        
if([defaults objectForKey:@"firstRun"])           
{
  // do something or not...
}
paulthenerd
A: 

In your app delegate register a default value:

NSDictionary *defaultsDict = 
[[NSDictionary alloc] initWithObjectsAndKeys:[NSNumber numberWithBool:YES], @"FirstLaunch", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultsDict];
[defaultsDict release];

Then where you want to check it:

NSUserDefaults *sharedDefaults = [NSUserDefaults standardUserDefaults];
if ([sharedDefaults boolForKey:@"FirstLaunch"]) {
  //Do the stuff you want to do on first launch
  [sharedDefaults setBool:NO forKey:@"ShowAutofillHint"];
  [sharedDefaults synchronize];
}
Louis Gerbarg
+1  A: 

Use NSUserDefaults. If the sharedDefault has a key for your app, its run before. Of course, you'll have to have the app create at least one default entry the first time the app runs.

TechZen