I am trying to implement the Singleton pattern on my app, without success so far. When I try to access my Singleton, it seems that the program is not accessing the real singleton, but a copy of it instead. Since this copy was not initialized, my app crashes, showing this error:
fatal error: unexpectedly found nil while unwrapping an Optional value
Here is an example of code I made:
import UIKit
class ViewController: UIViewController {
static let sharedViewController = ViewController()
var name: String = "Billy"
var age: Int = 12
override func viewDidLoad() {
super.viewDidLoad()
println("Old name from ViewController: \(name)")
println("Old age from ViewController: \(age)")
name = "Jack"
age = 45
println("New name from ViewController: \(name)")
println("New age from ViewController: \(age)")
println("singleton name from ViewController: \(ViewController.sharedViewController.name)")
println("singleton name from ViewController: \(ViewController.sharedViewController.age)")
}
}
As you can see, this is very simple. The class has two attributes initialized at creation, which are modified in viewDidLoad()
. First, I try to access the attributes directly, and, then, through the Singleton.
Here is the output:
Old name from ViewController: Billy
Old age from ViewController: 12
New name from ViewController: Jack
New age from ViewController: 45
singleton name from ViewController: Billy
singleton name from ViewController: 12
As you can see, the data is still the same from the singleton point of view. Unfortunately, the young Billy will never grow up.
I implemented all the three approaches of Singleton pattern in Swift, as it was said on this topic: dispatch_once singleton model in swift, without any success.
I do not understand why I cannot access the real Singleton and only a copy of it (which is bad for a Singleton pattern).
Thank you for your help.
I think, eventually, you won't be making a singleton of an
UIViewController
. What you probably want is to create a class, likePerson
.Still if you wan't to do it like you did
static let sharedViewController = ViewController()
isn't the same object asself
.Console :
Anyway, try to document yourself a bit more on the Singleton pattern :-)