ios - 具有许多 UIView 的单例服务

标签 ios swift delegates singleton nsnotificationcenter

学得很快,只卡在一个问题上。我正在尝试将委托(delegate)与 singleton 服务一起使用。
使用委托(delegate)我想更新多个 View ,但由于 singleton 实现委托(delegate)保留最后一个 UIView。
例如,我有 3 个 UIView,ID 分别为 1、2、3。当我在 init body self.myservice.delegate = self 中执行操作时,将尝试使用特定的委托(delegate)方法前。 myServiceDidUpdate 然后在此委托(delegate)方法中访问 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)
    }
}

最佳答案

你可以保留一个 uid 数组,但是多观察者的最佳实践是

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

关于ios - 具有许多 UIView 的单例服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53547184/

相关文章:

swift - 在 Swift 的 case 语句中赋值的 2 种方式

ios - 带有来自 plist 的数据的 objective-c 过滤 TableView

ios - 即使在 CLLocationManager 上明确调用 stopUpdatingLocation 后,状态栏上的位置服务指示器仍然出现

ios - 如何使用枚举而不是三种不同的状态?

ios - Flash builder 在发布版本中包含文件

ios - 更好的可点击表格 View 单元格的可访问性标签

ios - 检查一个整数是否可以被另一个整数整除(Swift)

objective-c - 转换 if ((loc = [player locateCardValue :8]) > - 1) to Swift 3

c# - 使用 Moq 测试接受委托(delegate)的方法

c# - 帮助理解 .NET 委托(delegate)、事件和事件处理程序