Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add settings to my cocoa application in swift?

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!

like image 473
TDM Avatar asked Nov 06 '15 17:11

TDM


2 Answers

The NSUserDefaults class is very easy to use in code, and its shared instance is readily available for binding to controls in 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:

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:

enter image description here

 

I would recommend reading the "Preferences and Settings Programming Guide", and also to familiar yourself with the "NSUserDefaults Class Reference".

like image 125
ElmerCat Avatar answered Sep 22 '22 19:09

ElmerCat


SWITF 5.x

The class changed the name so now you do:

UserDefaults.standard.set("1234", forKey: "userID")

To set a key that can hold any type. Or you can be type specific like this

UserDefaults.standard.bool(forKey: "IsConfigured")

The UI binding still working in the same fashion @ElmerCat well explained.

like image 26
amok Avatar answered Sep 19 '22 19:09

amok