Reputation: 601
I have a situation where I want to have two singleton objects that hold references to each other.
ManagerA:
import Foundation
class ManagerA: NSObject {
static let sharedInstance = ManagerA()
let managerB = ManagerB.sharedInstance
private override init() {
super.init()
}
}
ManagerB (in this example symmetric to ManagerA):
import Foundation
class ManagerB: NSObject {
static let sharedInstance = ManagerB()
let managerA = ManagerA.sharedInstance
private override init() {
super.init()
}
}
Manager A is being created in the AppDelegate. Unfortunately this leads to the ViewController not being shown anymore, so I assume the initialization process is endless.
How can I solve the initialization?
I'd like to stay with the pattern. Both managers are used throughout the app from various places and the singleton pattern seems fit. Yet it'd be useful if they could also directly access each other.
Upvotes: 4
Views: 581
Reputation: 59526
Yes, this is infinite recursion.
You can fix that in several ways.
Here I am making one of the 2 properties a computed property, look
final class ManagerA {
static let sharedInstance = ManagerA()
var managerB = { return ManagerB.sharedInstance }
private init() { }
}
final class ManagerB {
static let sharedInstance = ManagerB()
let managerA = ManagerA.sharedInstance
private init() { }
}
However do you really need a property to reference a singleton? The beauty of a singleton is that you can retrieve the only allowed instance of a class from everywhere simply writing ClassName.sharedInstance
.
So you could easily remove both the managerA
and managerB
properties.
NSObject
stuff since you don't really need that don't you?final
, otherwise someone could subclass them, add an init and break the singletons paradigmUpvotes: 4