mardi 9 juin 2015

Swift - Issue trying to access to Singleton object

This is my first question on StackOverflow, I'll try to be specific.

I am trying to implement the Singleton pattern on my app, without success so far. When I try to access to my Singleton, it seems that the program is not accessing the real singleton, but a copy of it which was not initialized, making my app crash with this error every time I try to access to anything:

fatal error: unexpectedly found nil while unwrapping an Optional value

Here is an example of code I made to show you my problem :

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 to attributes directly, then passing by 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 it seems that I cannot access the real Singleton and only a copy of it (which is bad for a Singleton pattern).

Thank you for your help, have a good day !

Aucun commentaire:

Enregistrer un commentaire