Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create singleton with parameter in swift:

I have the following class:

class FeedDataManager: URLManagerdelegate {

let TAG: String = "FeedDataManager"

weak var mDelegate: KeyboardViewController?

var mModelManager: ModelManager!
var mURLManager: UrlManager!
var mGetNewsTimer: NSTimer?

var mFeedsArray: Array<News>!

var mManagedObjectContext: NSManagedObjectContext!
var mPersistentStoreCoordinator: NSPersistentStoreCoordinator!
var mManagedObjectModel: NSManagedObjectModel!

class var sharedInstance: FeedDataManager {
    struct Static {
        static var onceToken: dispatch_once_t = 0
        static var instance: FeedDataManager? = nil
    }

    dispatch_once(&Static.onceToken) {
        Static.instance = FeedDataManager()
    }
    return Static.instance!
}

init (aDelegate: KeyboardViewController) {
    self.mDelegate = aDelegate
}
}

The Problem: If you look at the init method you will see that it should receive as a parameter a delegate pointer that I want to store in the singleton, so basically I need to pass this parameter to this line:

Static.instance = FeedDataManager()

But I have no idea how it's done, Does any knows how this can be done?

BTW: I saw this link: Singleton and init with parameter But the singleton creation there is different.

like image 875
Emil Adz Avatar asked Aug 29 '26 00:08

Emil Adz


1 Answers

We can show you how you can add parameter to declaration of singleton, but that's not really a good idea. The entire idea behind a singleton is that it doesn't matter where it is instantiated, you can use it anywhere. What does it mean if you invoked this singleton in two different places in your code, with different parameters? You have a race condition, where the behavior may change depending upon where and how the singleton was first encountered.

Unrelated, but the dispatch_once is redundant. The static variables are already employed with dispatch_once. See discussion at end of http://developer.apple.com/swift/blog/?id=7 (this is primarily geared towards globals, but as they parenthetically point out, it applies to static variables, too). Also, in Swift 1.2, we can now have static class variables, eliminating the need for the struct, too

like image 139
Rob Avatar answered Aug 31 '26 14:08

Rob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!