jeudi 2 juin 2016

Singleton re-entering init function in Swift 2

I have a singleton class as below:

public class MyClass {
    public static let mySingletonClass = MyClass()

    public var aValue: Int

    private init(){
        self.resetValue()
    }

    func resetValue(){
        aValue = 0
    }
}

and I have 2 view controllers namely viewControllerOne and viewControllerTwo. In viewControllerOne class I define a variable mySingletonClass as below:

import UIKit

class ViewControllerOne: UIViewController
    let mySingletonClass = MyClass.mySingletonClass

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

And later in the viewControllerOne I change the "aValue" value of mySingletonClass.

Now the problem is: when I navigate from viewOne to viewTwo the "aValue" value in mySingletonClass resets back to 0.

How can I make it not reset everytime? Is this how to implement a singleton?

Thank you

Aucun commentaire:

Enregistrer un commentaire