开发者

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 开发者_StackOverflow社区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.


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.


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


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];

    }

}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜