Detecting the initial launch of an app using NSUserDefaults

空扰寡人 提交于 2019-12-04 21:49:08

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!