darksky
darksky

Reputation: 21069

Detecting the initial launch of an app using NSUserDefaults

In reference to the following question: iPhone: How do I detect when an app is launched for the first time?

When I looked up NSUserDefaults apple reference, it said that registerDefaults does not store the data onto the disk. In the above question, the app registers the value firstLaunch to YES upon each launch. So each time the app is launched, firstLaunch is overwritten to YES and so the app will always think that this is the app's initial launch.

Am I right on this?

EDIT:

After doing what the tutorial above says, it doesn't always work anyway. I keep relaunching from Xcode and it keep printing out 1 bool value as in its the first launch.

Upvotes: 1

Views: 1524

Answers (4)

omz
omz

Reputation: 53561

registerDefaults: doesn't overwrite existing values, it only initializes values that aren't set to any value yet.

Upvotes: 1

Hollance
Hollance

Reputation: 2976

registerDefaults: doesn't overwrite what is already in the defaults, but it sets defaults-for-the-defaults. So if a default is missing it uses a default-default. Confusing, isn't it?

If you've never written a value under the key FirstLaunch, then boolForKey:@"FirstLaunch" will use the value from registerDefaults:. However, if you did previously do setBool:NO forKey:@"FirstLaunch" and later ask for it again with boolForKey: then the value from registerDefaults: is not used.

Upvotes: 5

kviksilver
kviksilver

Reputation: 3854

Try something like this in

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

if ([[[NSUserDefaults standardUserDefaults] valueForKey:@"firstRun"] intValue]==0) {
       //do the stuff required at first launch


//after stuff done
    [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:1] forKey:@"firstRun"];
    [[NSUserDefaults standardUserDefaults] synchronize];

    }

}

Upvotes: 0

Rahul Vyas
Rahul Vyas

Reputation: 28750

NO first it will be nil then you set it to yes and before setting it to yes check if it's already set to yes or not. So first time userDefaults will return nil if you get something for a key. like

[[NSUserDefaults standardUserDefaults] valueForKey:@"FirstLaunch"]; 

will return nil on first launch of application.

Upvotes: -1

Related Questions