首页 > 解决方案 > 具有许多 UIView 的单例服务

问题描述

学习迅速,只遇到一个问题。我正在尝试将代表与singleton服务一起使用。
使用委托我想更新多个视图,但由于singleton实现委托保留最后一个 UIView。
因此,例如,我有 3 个 ID 为 1、2、3 的 UIView。当我将在init正文中执行self.myservice.delegate = self并尝试使用特定的委托方法时。myServiceDidUpdate然后在这个委托方法中访问self.viewId总是返回last id
我想这是由于singleton服务实施的原因,想向您寻求帮助。

注意:我需要单例实现来保持特定变量的服务

问题:是否可以保留我的服务的 3 个实例并在我需要的服务中保持变量?或者处理这个问题的最佳方法是什么

代码

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

我的服务

class AudioService {
    static let shared = AudioService()
    var delegate: AudioServiceDelegate?
    var identifier: String?

    ...

    @objc func didUpdate(_ notification: Notification) {
        self.delegate?.myServiceDidUpdate(self.identifier)
    }
}

标签: iosswiftdelegatessingletonnsnotificationcenter

解决方案


您可以保留一组 uids ,但多观察者的最佳做法是

// 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 用于 1-1 观察,notificationCenter 用于 1-m


推荐阅读