这是什么意思:“线程1:”-[[First_App.ProximitySensorViewController接近性更改:]:无法识别的选择器已发送到实例0x14d707940”

问题描述

嘿,我试图使用接近传感器来增加一个值,但是当我启动该功能时,它崩溃了。这是我的密码,有人可以帮我吗?

func proximityChanged(notification: NSNotification) {
            let device = notification.object as? UIDevice
            if device?.proximityState == true {
                print("\(device) detected!")
                count += 1
                updateCountLabel()
            } else {
                print("Error")
            }
        }
        
        
        func activateProximitySensor() {
            let device = UIDevice.current
            device.isProximityMonitoringEnabled = true
            if device.isProximityMonitoringEnabled {
                NotificationCenter.default.addobserver(self,selector: Selector(("proximityChanged:")),name: NSNotification.Name(rawValue: "UIDeviceProximityStateDidChangeNotification"),object: device)
                
            }
        }

解决方法

我认为您可能正在使用旧语法来快速处理。我尝试使用下面的代码使用接近度,并且没有崩溃。

func activateProximitySensor() {
    let device = UIDevice.current
    device.isProximityMonitoringEnabled = true
    if device.isProximityMonitoringEnabled {
        NotificationCenter.default.addObserver(self,selector: #selector(proximityChanged(notification:)),name: UIDevice.proximityStateDidChangeNotification,object: device)
    }
}

@objc func proximityChanged(notification: NSNotification) {
    if let device = notification.object as? UIDevice {
        if device.proximityState {
            print("\(device) detected!")
            count += 1
            updateCountLabel()
        }
    }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...