在哪里使用 Userdefaults

Where to use Userdefualts

我有一个应用程序使用与视图控制器相对应的文件,但是我想在我的程序中包含 userdefaults (NSuserdefaults)。我将在哪里创建它,如

let defaults = NSUserDefaults.standardUserDefaults()

我应该在哪里创建用户默认值?我会把它放在一个单独的文件中吗? viewcontroller 文件用于说一个开始屏幕?或者我会为 NSuserdefualt 创建一个文件并在其他 viewcontroller 文件中调用它吗?

NSUserDefaults

The NSUserDefaults class provides a programmatic interface for interacting with the defaults system. The defaults system allows an application to customize its behavior to match a user’s preferences. For example, you can allow users to determine what units of measurement your application displays or how often documents are automatically saved. Applications record such preferences by assigning values to a set of parameters in a user’s defaults database. The parameters are referred to as defaults since they’re commonly used to determine an application’s default state at startup or the way it acts by default.

您可以在源代码中的任何地方调用它,因为它是一个单例 class。您通常使用它来存储用户设置。

你可以参考这个,关于如何在Swift3和Swift2.3

中使用它

你真的可以把它放在任何地方。把它想象成改变一个变量的值——你可以把那个函数放在哪里。

这是一个例子:

let highscore = 1000  //this is the value
//below is the saving part
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setValue(highscore, forKey: "highscore")
userDefaults.synchronize()

我可以随时更改并保存值时放置保存部分。比如你可以把它放在一个按钮的一个Action里,放在viewdidload里等等。 然后通常你 'load' 当你通过将加载代码(不包括在这个答案中)放在 viewDidLoad 中进入应用程序时再次 'load' 它,但你也可以将它放在按钮操作,功能等中。