代码之家  ›  专栏  ›  技术社区  ›  cpd1

更新由计时器驱动的函数中的变量

  •  0
  • cpd1  · 技术社区  · 6 年前

    我有下面的功能,当一个按钮被切换到激活状态时,它可以正常工作。我想添加一个变量,它为每条消息提供从1开始的当前消息编号。我尝试过不同的设置/更新值的方法,但这些方法都没有帮助更新。

    我对Swift/iOS开发非常陌生,所以我确信我遗漏了一些东西。我所知道的是,消息反复打印到控制台,直到按钮关闭,并且 Timer 使它能够连续运行。

    @IBOutlet weak var stateLabel: UILabel!
    //Starts / Stops recording of sensor data via a switch
    @IBAction func stateChange(_ sender: UISwitch) {
        if sender.isOn == true {
            startSensorData()
            stateLabel.text = "Stop"
        } else {
            stopSensorData()
            stateLabel.text = "Start"
        }
    }
    
    
    func startSensorData() {
        print("Start Capturing Sensor Data")
        // Making sure sensors are available
        if self.motionManager.isAccelerometerAvailable, self.motionManager.isGyroAvailable {
    
            // Setting the frequency required for data session
            self.motionManager.accelerometerUpdateInterval = 1.0 / 3.0
            self.motionManager.gyroUpdateInterval = 1.0 / 3.0
    
            // Start sensor updates
            self.motionManager.startAccelerometerUpdates()
            self.motionManager.startGyroUpdates()
    
            // Configure a timer to fetch the data.
            self.motionUpdateTimer = Timer.scheduledTimer(withTimeInterval: 1.0/3.0, repeats: true, block: { (timer1) in
                // Get the motion data.
                var loggingSample = 1
                if let accelData = self.motionManager.accelerometerData, let gyroData = self.motionManager.gyroData {
    
                    let accelX = accelData.acceleration.x
                    let accelY = accelData.acceleration.y
                    let accelZ = accelData.acceleration.z
    
                    let gyroX = gyroData.rotationRate.x
                    let gyroY = gyroData.rotationRate.y
                    let gyroZ = gyroData.rotationRate.z
    
                    let message = "\(Date().timeIntervalSince1970),\(self.device_id),\(loggingSample),\(accelX),\(accelY),\(accelZ),\(gyroX),\(gyroY),\(gyroZ),Processing"
                    print(message)
                    loggingSample += 1
                }
            }
        )}
    }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   rmaddy    6 年前

    你一直得到的价值 1 对于 loggingSample 因为您使用的局部变量 每一次。

    你所要做的就是移动声明 测井样本 在函数之外,因此它是类属性。

    移动线路:

    var loggingSample = 1
    

    在功能之外,所以它靠近您的插座和其他属性。