2

I have objective / swift code side by side. I am calling a swift singleton method 3 times. After three times it crashes. I have reason to believe this might be a memory problem. Here is my code

ViewController.m

-(void)sharedData
{
    // called three times
    sharedData = [SharedData sharedData];
    [sharedData initSyncManager];
}

Swift sharedData class

class func sharedData() -> SharedData 
{
    struct Singleton 
    {
        static let instance = SharedData()
    }
    return Singleton.instance
}

func initSyncManager()
{

}

The error is EXC_BAD_ACCESS (code=EXC_i386_GPFLT) on this line

'return Singleton.instance'

I have no idea why this is occurring. I have no code in initSyncManager at all and this crash only happens when I use this piece of code

[sharedData initSyncManager];

If I don't call the method 3 times, the crash doesn't occur.

William Alex
  • 385
  • 1
  • 3
  • 14
  • I think you have a problem creating singleton, read this http://code.martinrue.com/posts/the-singleton-pattern-in-swift – iphonic Mar 16 '15 at 17:33
  • I tried the singleton presented and it didn't work sadly. – William Alex Mar 16 '15 at 17:48
  • 3
    Best implementation of an singleton: not at all. I am serious. Step back and ask yourself: "does it really need to be an singleton?", I for example don't use them anymore, I just pass in any object that is needed during creation of a view controller or pass it via properties. Why? because Singletons easily mess up your testing, and memory. – vikingosegundo Mar 16 '15 at 18:09

2 Answers2

1

You may try this, as I am using this (in Swift 2.1) for creating singleton classes and it's working fine for me:

class var sharedInstance: SharedData {
    struct Static {
        static var onceToken: dispatch_once_t = 0
        static var instance: SharedData? = nil
    }
    dispatch_once(&Static.onceToken) {
        Static.instance = SharedData()
    }
    return Static.instance!
}

override init() {
    super.init()
    //initialisation
}
D4ttatraya
  • 3,344
  • 1
  • 28
  • 50
0

I don't think your singleton syntax is working like you expect it to and is creating a new instance with each instantiation. With each instantiation, you're calling static let instance = SharedData() ("give me a new instance of shared data") and then returning it.

Try this instead:

private let _SharedData = SharedData()

class SharedData {
    class var instance: SharedData {
        return _SharedData
    }
}
brandonscript
  • 68,675
  • 32
  • 163
  • 220