ios - 传入 DispatchQueue 后变量变为 0(在模拟器中工作。在实际设备中为 0)
问题描述
变量(以秒为单位的锻炼时间)没有传递到 GCD 函数调用的代码有问题。但是 workoutStartDateTime
通过没有问题。这是我正在使用的代码。
var seconds: Int = 0
var workoutStartDateTime: Date?
func finishWorkout() {
print("0 FinishWorkout:\(seconds) workoutStartDateTime:\(workoutStartDateTime)")
DispatchQueue.global(qos: .utility).async { [self] in
print("1 FinishWorkout:\(self.seconds) workoutStartDateTime:\(workoutStartDateTime)")
TCXfuncs.writeTCX(workoutStartDateTime: workoutStartDateTime!, seconds: seconds)
}
这是打印出来的
0 FinishWorkout:3 workoutStartDateTime:Optional(2021-01-28 03:05:29 +0000)
1 FinishWorkout:0 workoutStartDateTime:Optional(2021-01-28 03:05:29 +0000)
// I also placed a print statement into the TCXFunc function to verify.
TCXExportFunction seconds:0
奇怪的是,当我在模拟器中运行它时,它可以工作。通过的秒数。
0 FinishWorkout:3 workoutStartDateTime:Optional(2021-01-28 03:05:29 +0000)
1 FinishWorkout:3 workoutStartDateTime:Optional(2021-01-28 03:05:29 +0000)
// I also placed a print statement into the TCXFunc function to verify.
TCXExportFunction seconds:3
编辑:(和解决方案)
经过多次尝试和 SO/Google,我发现了这个 SO --> https://stackoverflow.com/a/31566063/14414215并使用它。现在的问题是为什么
func finishWorkout() {
let mySec = seconds
print("0 FinishWorkout:\(seconds) mySec:\(mySec) workoutStartDateTime:\(workoutStartDateTime)")
DispatchQueue.global(qos: .utility).async { [self] in
print("1 FinishWorkout:\(self.seconds) mySec:\(mySec) workoutStartDateTime:\(workoutStartDateTime)")
TCXfuncs.writeTCX(workoutStartDateTime: workoutStartDateTime!, seconds: mySec) // << Pass the "helper" variable
}
这是结果输出。您可以看到 119 在第二次打印输出中变为“0”,“helper”变量使其正确。为什么.....?
0 FinishWorkout:119 mySec:119 workoutStartDateTime:Optional(2021-01-28 04:04:33 +0000)
1 FinishWorkout:0 mySec:119 workoutStartDateTime:Optional(2021-01-28 04:04:33 +0000)
// I also placed a print statement into the TCXFunc function to verify.
writeTCX Passed seconds:119 Date:2021-01-28 04:04:33 +0000
解决方案
我认为这是一个时间问题。“dispatch.async()”调用的意思是“在将来的某个地方做这个”。这可能很快(微秒)甚至很晚(毫秒),但您的应用程序的其他部分可能会同时重置“秒”。
当您在提交调度调用之前将当前内容“保存”到局部变量中时,只要调度项开始工作,您就可以使用此值。
推荐阅读
- roku - 在 Roku 中使用 SubString 作为函数
- nlp - 我们可以使用生成对抗网络进行神经机器翻译吗?
- php - Codeigniter 使用 SELECT_SUM,只返回第一列
- python-3.x - Binning with pd.Cut Beyond range(replacing Nan with "
Max_val" ) - c++ - 为什么 std::atomic 的默认构造函数不默认初始化底层存储值?
- python - keras-gcn 拟合模型 ValueError
- kubernetes - 为什么我的入口控制器没有将流量从我的外部 IP 路由到集群中的服务?
- android - 有没有办法通过 React Native 使用 Microsoft LUIS?
- c# - 打开新表单后更改按钮的可见性
- javascript - 无法读取 Angular 8 中未定义的属性“卡片”