TDM
TDM

Reputation: 814

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!

Upvotes: 8

Views: 4326

Answers (2)

amok
amok

Reputation: 1745

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.

Upvotes: 5

ElmerCat
ElmerCat

Reputation: 3155

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".

Upvotes: 21

Related Questions