问题
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)
}
}
回答1:
You can keep an array of uids , but the best practice for multi-observer is
// add observer wherever you want to register for new data
notificationCenter.addObserver(self,
selector: #selector(self.calledMeth),
name: .didReceiveData,
object: nil)
//
// post when you want to publish data
NotificationCenter.default.postNotification(name: .didReceiveData, object: nil)
extension Notification.Name {
static let didReceiveData = Notification.Name("didReceiveData")
static let didCompleteTask = Notification.Name("didCompleteTask")
}
Delegate is used for 1-1 observing while notificationCenter is used for 1-m
来源:https://stackoverflow.com/questions/53547184/singleton-service-with-many-uiviews