borchero
borchero

Reputation: 6002

Store data in Swift

I have a general question on programming related to Swift. For example when I want to store a Int value in my app because I use this variable along the whole application. So I have three options for this:

//FIRST
//In my AppDelegate I do this
var myInt = 3
//And later I can use this when I do
let delegate = UIApplication.sharedApplication().delegate as AppDelegate
delegate.myInt = 5

//SECOND
//I can store the value in UserDefaults
NSUserDefaults.standardUserDefaults().setInteger(myInt, forKey: "myInt")
NSUserDefaults.standardUserDefaults().synchronize()
//and later get them by
var anotherInt = NSUserDefaults.standardUserDefaults().integerForKey("myInt")

//THIRD
//I can define a structure as my Data storage
struct myData {
    static var myInt = 3
}
//and later get the value by
myData.myInt = 5

So my question is, which one should I use? Or shouldn't one store any global values at all? Would love to hear from you :]

Upvotes: 0

Views: 318

Answers (1)

SirNod
SirNod

Reputation: 781

Option 1 would work fine if you don't want the variable to persist between app launches.

Option 2 would work fine if you do want the variable to persist between app launches.

Option 3 would also work but is not persistent.

I would say option 1 or 2 are the more commonly used, depending on if you need the variable to be persistent.

Upvotes: 1

Related Questions