我有以下代码来观察通过KVO在Swift中的白平衡变化。
self.addObserver(self, forKeyPath: "videoInput.device.deviceWhiteBalanceGains", options: [.new, .old], context: &whitebalanceGainsObserverContext)
然后在观察值(…)中,我这样做:
if context == &whitebalanceGainsObserverContext {
if let newNSValue = change?[.newKey] as? NSValue {
var gains = AVCaptureDevice.WhiteBalanceGains()
newNSValue.getValue(&gains)
/* Crashes here on some devices in AppStore, throws an exception */
let newTemperatureAndTint = self.videoInput?.device.temperatureAndTintValues(for: gains)
}
}
我再也无法重现坠机的情景,所以我想知道如何避免坠机。为了避免抛出异常,我应该进行哪些检查?
编辑:我还尝试使用新的观察API,如下所示:
deviceWBGainsObservation = observe(\.videoInput?.device.deviceWhiteBalanceGains, options: [.old, .new]) { (obj, change) in
if let newNSValue = change.newValue {
}
}
即使这样,
deviceWBGainsObservation = videoDevice?.observe(\.deviceWhiteBalanceGains, options: [.old, .new]) {[unowned self] (object, change) in
if let newNSValue = change.newValue {
}
}
还有这个:
private var videoDevice:AVCaptureDevice? {
didSet {
deviceWBGainsObservation = videoDevice?.observe(\.deviceWhiteBalanceGains, options: [.old, .new]) {[unowned self] (object, change) in
if let newNSValue = change.newValue {
}
}
}
问题是在这种情况下,更改值总是为零。为什么?