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

      

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

Static.instance = FeedDataManager()

      

But I have no idea how this is done, does anyone know how it can be done?

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

+3


source to share


1 answer


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



Unrelated but dispatch_once

redundant. Variables are static

already in use with dispatch_once

. See the discussion at the end of http://developer.apple.com/swift/blog/?id=7 (this is primarily geared towards globals, but as they indicate in parentheses, this also applies to variables static

). Also, in Swift 1.2 we can now have static class variables, eliminating the need for struct

, too

+9


source







All Articles