How does NSUserDefaults registerDefaults work? [duplicate]

寵の児 提交于 2019-12-06 03:42:47

问题


When i set registerDefaults in application:didFinishLaunchingWithOptions: i set the default values for the NSUserDefaults throught the app.

NSMutableDictionary *defaultsDictionary = [@{@"userHasLoggedInOnce":@NO, @"firstTimeOpeningApp":@YES} mutableCopy];

[[NSUserDefaults standardUserDefaults] registerDefaults:defaultsDict];
[[NSUserDefaults standardUserDefaults] synchronize];

How does registerDefaults store that it has set these values only once, since its called every time on app start? Is it an own value thats also set as a standardUserDefaults value? If so, is it possible to reset the default values?


回答1:


Register user defaults sets default values, for the keys. So when the application starts for the first time, you won't get nil, 0 or false and then have to test a lot of times through your code if that's the case. Instead you set something like "Welcome".

Edit: The contents of the registration domain are not written to disk; you need to call this method each time your application starts. You can place a plist file in the application's Resources directory and call registerDefaults: with the contents that you read in from that file. (Source)

As the comment explained, calling registerUserDefaults doesn't override the savedValues, so you can safely call it each time the application launches. You can add a reset button, where you override the saved values by the user, with the values in your plist (defaults).



来源:https://stackoverflow.com/questions/19972367/how-does-nsuserdefaults-registerdefaults-work

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