William Alex
William Alex

Reputation: 415

iOS Swift: Calling a singleton method 3 times causes app to crash

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.

Upvotes: 2

Views: 2037

Answers (2)

D4ttatraya
D4ttatraya

Reputation: 3404

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
}

Upvotes: 1

brandonscript
brandonscript

Reputation: 72965

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
    }
}

Upvotes: 0

Related Questions