I'm pretty new to programming in Swift, and I'd like to know if there is an easy way to add settings/preferences to my Cocoa application in Swift. If possible, I'd like a step by step guide. I mostly want to know how you store the user's preferences on disk and the code part. In my current code it will need to check which setting the user has chosen, and based on that perform an action. I'm using Xcode 7.1 and Swift 2. Thanks in advance!
我对Swift中的编程很新,我想知道是否有一种简单的方法可以在Swift中为我的Cocoa应用程序添加设置/首选项。如果可能的话,我想要一步一步的指导。我主要想知道如何将用户的首选项存储在磁盘和代码部分。在我当前的代码中,它需要检查用户选择了哪个设置,并根据该设置执行操作。我正在使用Xcode 7.1和Swift 2.提前感谢!
1 个解决方案
#1
10
The NSUserDefaults
class is very easy to use in code, and its shared instance is readily available for binding to controls in Interface Builder.
NSUserDefaults类非常易于在代码中使用,并且其共享实例可用于绑定到Interface Builder中的控件。
For example, if I wanted to have an integer preference named "elmer" and set its value to 7, it's as easy as:
例如,如果我想要一个名为“elmer”的整数首选项并将其值设置为7,那就很简单:
NSUserDefaults.standardUserDefaults().setInteger(7, forKey: "elmer")
To read the value back:
要读回值:
let elmer: Int = NSUserDefaults.standardUserDefaults().integerForKey("elmer")
To bind the value to a control in Interface Builder, set the Controller Key to "values", and the preference name for the Model Key Path:
要将值绑定到Interface Builder中的控件,请将Controller Key设置为“values”,并将Model Key Path的首选项名称设置为:
I would recommend reading the "Preferences and Settings Programming Guide", and also to familiar yourself with the "NSUserDefaults Class Reference".
我建议阅读“首选项和设置编程指南”,并熟悉“NSUserDefaults类参考”。
#1
10
The NSUserDefaults
class is very easy to use in code, and its shared instance is readily available for binding to controls in Interface Builder.
NSUserDefaults类非常易于在代码中使用,并且其共享实例可用于绑定到Interface Builder中的控件。
For example, if I wanted to have an integer preference named "elmer" and set its value to 7, it's as easy as:
例如,如果我想要一个名为“elmer”的整数首选项并将其值设置为7,那就很简单:
NSUserDefaults.standardUserDefaults().setInteger(7, forKey: "elmer")
To read the value back:
要读回值:
let elmer: Int = NSUserDefaults.standardUserDefaults().integerForKey("elmer")
To bind the value to a control in Interface Builder, set the Controller Key to "values", and the preference name for the Model Key Path:
要将值绑定到Interface Builder中的控件,请将Controller Key设置为“values”,并将Model Key Path的首选项名称设置为:
I would recommend reading the "Preferences and Settings Programming Guide", and also to familiar yourself with the "NSUserDefaults Class Reference".
我建议阅读“首选项和设置编程指南”,并熟悉“NSUserDefaults类参考”。