如何在Timer闭包中更新@Published值且无并发警告?
Swift Concurrency警告:Recorder类计时器闭包捕获self的问题
我有以下代码:
class Recorder: ObservableObject { @Published var recordingTimeSeconds: TimeInterval = 0 private var timer: Timer? init() {} func startRecording() { timer = Timer(timeInterval: 1, repeats: true, block: { t in self.recordingTimeSeconds = t.timeInterval }) RunLoop.main.add(timer!, forMode: .common) } }
我的项目启用了-warn-concurrency编译标记,self.recordingTimeSeconds这一行出现警告:
Capture of 'self' with non-sendable type 'Recorder' in a '@Sendable' closure
原本以为以下方案不会产生警告:
编辑说明: 以下方案实际仍会触发相同警告,撰写问题时XCode未显示该警告
方案一:
Task { @MainActor [timeInterval = t.timeInterval] in self.recordingTimeSeconds = timeInterval }
方案二:
DispatchQueue.main.async { [seconds = t.timeInterval] in self.recordingTimeSeconds = seconds }
但我希望找到替代方案,因为使用DispatchQueue或Task可能在后续引发问题。我的场景中,计时器需要无延迟地更新该值。
内容的提问来源于stack exchange,提问作者MMise
相关产品推荐
相关产品推荐

