0

I want to create a global NSDate in my app, because I want to save the date of the first time ever the app has been opened in this variable. I wrote "var LaunchDate = NSDate()" before the declaration of the main class of the first view controller, and in the viewdidload, if it is the first time the app is opened, it saves the date into the global variable LaunchDate. But everytime I open the app, it saves the current date because of "var LaunchDate = NSDate()". I didn't find a solution, do you have any idea to declare a global date without that he gives the current date please?

Oscar Falmer
  • 1,771
  • 1
  • 24
  • 38

4 Answers4

4

You could use NSUserDefaults to store the value.

The code checks if a value exists.
If yes it reads the value, if no it writes the current date.

var launchDate : NSDate!

let defaults = NSUserDefaults.standardUserDefaults()
if let dateOfFirstLaunch = defaults.objectForKey("dateOfFirstLaunch") as? NSDate {
  launchDate = dateOfFirstLaunch
} else {
  let currentDate = NSDate()
  defaults.setObject(currentDate, forKey:"dateOfFirstLaunch")
  launchDate = currentDate
}
vadian
  • 274,689
  • 30
  • 353
  • 361
0

Try this:

override func viewDidLoad() {
    var LaunchDate: NSDate

    // when you want to set the value for it:
    LaunchDate = NSDate()
}

The Proble, is that NSDate() which you tried to do is a function, which gets back a value of the current date.

Tom el Safadi
  • 6,164
  • 5
  • 49
  • 102
0

Global variables are variables that are defined outside of any function, method, closure, or type context

struct globalDate 
{
   static var LaunchDate = NSDate()
}

In swift if you encapsulate the variable in struct, you can access that in any classes.

Document

Global Variable

Community
  • 1
  • 1
user3182143
  • 9,459
  • 3
  • 32
  • 39
0

I would use the Singleton Pattern with NSUserDefaults.

The code should be something like this

import Foundation

class UserDefaults {
    static let sharedInstance = UserDefaults()

    var launchDate: NSDate? {
        get {
            return NSUserDefaults.standardUserDefaults().objectForKey("launch_date") as? NSDate
        }
        set {
            NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: "launch_date")
        }
    }
}

Access it using this code

UserDefaults.sharedInstance.launchDate
Peba
  • 440
  • 4
  • 14