Is it possible to pass parameters to a Singleton class? If so how?
This is a snippet of one of my Singleton classes:
class NotificationManager: NSObject {
static let sharedManager = NotificationManager()
var tabBarController: UITabBarController!
private override init() {
super.init()
}
In the case of this Singleton, the public property tabBarController
must always be set before being used.
I'm wondering if its possible to pass the correct UITabBarcontroller
object on start up, as I assume this is when my Singleton class is being instantiated? This would prevent the class from ever being implemented incorrectly. Not that I ever expect this to be a problem as is.
Also, is it perfectly fine to use Singleton classes in this instance? To manage a specific set of operations? In the past I was always passing objects around, especially managedObjectContext
, however now I've found Singleton classes to make everything much cleaner, nicer, and safer (as there is only ever one stance) in large apps. I can understand passing objects between classes is fine for smaller apps, but once they can large it can get pretty messy.
In my most recent app I'm also using a shared Singleton class between my iOS and watchOS app that defines a few global variables, such as server endpoints, and environments. This appears to be the best way to go about defining variables that require this access.
I've had friends tell me that Singletons are bad to use, and from what I've Google'd, it really seems like a mixed bag. In my case, they have made my code way easier to manage, and handle.
Thanks.