Learning swift and just stuck with one issue. I'm trying to use delegates with singleton
service.
With delegate i want to update multiple views, but due to singleton
implementation delegate keeps last UIView.
So for example i have 3 UIViews with ids 1, 2, 3. When i'll do in init
body self.myservice.delegate = self
and will try to use specific delegate method ex. myServiceDidUpdate
then in this delegate method accessing self.viewId
always returning last id
.
I guess it's due to singleton
service implementation and wanted to ask you for help.
Note: I need singleton implementation to keep specific variable in service
Question: Is that possible to keep 3 instances of my service and also keep variable in that service i need? Or what's the best approach to handle this
Code
class SimpleView: UIView, AudioServiceDelegate {
private var audioService = AudioService.shared
var viewId: String?
override init(frame: CGRect) {
super.init(frame: frame)
self.viewId = NSUUID().uuidString
self.audioService.delegate = self
}
func myServiceDidUpdate(identifier: String?) { <-- identifier coming from service i need to keep it across multiple views
print("SELF", self.viewId) <-- Keeps always last initialized ID
}
}
MyService
class AudioService {
static let shared = AudioService()
var delegate: AudioServiceDelegate?
var identifier: String?
...
@objc func didUpdate(_ notification: Notification) {
self.delegate?.myServiceDidUpdate(self.identifier)
}
}