ios - 具有许多 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)
}
}
解决方案
您可以保留一组 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
推荐阅读
- python - 将循环中的列表移动到字符串
- android - 如何使用 4 个 EditTexts 和 addTextChangedListener 创建 PIN 输入?
- jetty - 如何在 Jetty 的透明代理 servlet 中处理分块响应
- java - 在基类中结合 Fragment 和 Activity 类
- swift - Swift:BLE 16 字节到 Int
- javascript - 如何将数组数据转换为新数据
- npm - 发现多个版本的 aurelia-dependency-injection
- php - 如何在 Google Content API(购物)中插入 customBatch
- bluetooth - 是否有在 ble 中获取连接的远程设备名称的选项?
- javascript - 如何防止竖线中的图例在 Chart.js 中重叠?