电池电量变化时未捕获NSException

时间:2017-06-24 17:00:10

标签: ios swift

我正在制作一个只显示时间和电池电量的简单应用。时间部分完美运行,我可以监控电池电量,但是当设备的电池发生任何变化时,电池指示器图标会崩溃应用程序。这是相关的代码:

override func viewDidLoad() {
    super.viewDidLoad()
    UIDevice.current.isBatteryMonitoringEnabled = true // Enable battery monitoring
    NotificationCenter.default.addObserver(self, selector: Selector(("batteryStateDidChange:")), name: NSNotification.Name.UIDeviceBatteryStateDidChange, object: nil) // Add battery state checker
    NotificationCenter.default.addObserver(self, selector: Selector(("batteryLevelDidChange:")), name: NSNotification.Name.UIDeviceBatteryLevelDidChange, object: nil) // Add battery level checker
    // Get the battery level
    var batteryLevel: Int {
        return Int(UIDevice.current.batteryLevel * 100)
    }
    update()
    timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(self.update), userInfo: nil, repeats: true) // Start the timed scheduler
}

这是错误:

2017-06-24 11:45:27.783761-0500 SimpleClock[1484:846193] -[SimpleClock.ViewController batteryLevelDidChange:]: unrecognized selector sent to instance 0x15dd15bc0
2017-06-24 11:45:27.785656-0500 SimpleClock[1484:846193] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[SimpleClock.ViewController batteryLevelDidChange:]: unrecognized selector sent to instance 0x15dd15bc0'
*** First throw call stack:
(0x181c65858 0x18043c528 0x181c72a6c 0x188815140 0x181c6af68 0x181b4ce5c 0x181bf3004 0x181bf25a4 0x181bf2308 0x181c74268 0x181b2a4e4 0x1826f32d4 0x1884abd60 0x1884abbc8 0x181ecdaf0 0x181beda68 0x181c0cbc8 0x181c0c370 0x181c09d80 0x181b28280 0x183639f94 0x1884d70f0 0x100da10e4 0x180919e40)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

2 个答案:

答案 0 :(得分:1)

-[SimpleClock.ViewController batteryLevelDidChange:]: unrecognised selector错误表示代码中缺少batteryLevelDidChange函数或Vadian注释,签名错误。

答案 1 :(得分:0)

在添加if condition选择器的观察者之前使用batteryStateDidChange:。您可以使用respondsToSelector:方法。这样就可以确保选择器是否已实现。

此外,您需要在源文件中实现选择器,因为我无法在您的代码中看到它,因此会出现unrecognised selector错误。

希望它有所帮助!