首页 > 解决方案 > 访问时的 EXC_BAD_ACCESS != nil static var

问题描述

上下文:应用程序需要 100% 的时间连接到蓝牙设备。在使用应用程序时,CBPeripheral 对象存储在一个静态变量中,供用户在应用程序中的整个会话期间使用。

//This is in AppDelegate class.
static var connectedDevice: CBPeripheral? = nil

…………

class BluetoothScanner : NSObject, CBCentralManagerDelegate, CBPeripheralDelegate {


//(...)

func connectToDevice(peripheral: CBPeripheral)
 {
    AppDelegate.connectedDevice = peripheral
    
    //(...)
    
 }

}

在应用程序启动时,对该变量的访问操作在循环中发生。对变量的第一次访问是正确的。但总是,在结束循环之前(大约 40 次访问 var),它会发生 EXC_BAD_ACCESS

        if(AppDelegate.connectedDevice != nil)
        {
          //Thread 3: EXC_BAD_ACCESS (code=2, address=0x16ec8ff28)  
          print("Device debug: " +  AppDelegate.connectedDevice!.debugDescription)
          
        }

调用“debugDescription”时会出现问题,但调用“connectedDevice”的任何其他函数时也会出现同样的问题

AppDelegate.connectedDevice 仅被访问(在那个时期),它从未被修改,也不会被释放。

我已经非常彻底地测试了该应用程序两周,没有出现任何问题。但是当将它上传到 AppStore 时,它​​表明我需要将 XCode 更新到最新版本才能将编译上传到 AppStore。没有接触代码就出现了这个问题,只更新了XCode。我什至测试过(在更新 XCode 之前)这个对象在应用程序的使用时间内不会被释放。

标签: iosswiftiphonexcodeswift5

解决方案


推荐阅读