Search code examples
singletonswift3observersinitwithcoder

Having a singleton use the value from initWithCoder instead of creating a new instance in Swift


I have a simple boolean variable in a function on which a set an observer to check when it changes:

var userValid: Bool{
    didSet{
        let valid=userValid ? "valid" : "not valid"
        print("uservalid changed to \(valid)")
    }
}

I set it to false in the init and then to true in the program: the initialiser is called twice once for the class and once for the subclass but I am alway checking the value in the class. So I am seeing the variable is set to true in the observer, but then when I check it in another function I find it at false without the observer to be ever called again.

As it comes out the problem seems to stem from the fact I initialise two times the class: once as a singleton and the other one with:

init?(coder aDecoder: NSCoder)

Of course I initialise the singleton with:

public class func sharedMapDelegate() -> MapDelegate {
    struct Static {
        static let instance : MapDelegate = MapDelegate()
    }
    return Static.instance
}

How may I return the value generated from the initWithCoder instead of creating a new one?


Solution

  • I think I have fixed it by changing the singleton to:

    public class func sharedMapDelegate() -> MapDelegate {
        struct Static {
            static var instance : MapDelegate {
                if let me = Factory.sharedFactory().mapHandler {
                    return me
                } else {
                    Factory.sharedFactory().mapHandler=MapDelegate()
                    return Factory.sharedFactory().mapHandler
                }
            }
        }
        return Static.instance
    }