watchOS应用中CMFallDetectionManager崩溃:无效CMFallDetectionDelegate
问题
在watchOS应用中尝试使用CMFallDetectionManager实现跌倒检测功能,模拟跌倒时应用崩溃,崩溃信息如下:
"Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'invalid CMFallDetectionDelegate'"
已完成以下操作:
- 创建
CMFallDetectionManager实例并将其delegate赋值给符合CMFallDetectionDelegate协议的代理类 - 在代理类中实现了指定方法:
func fallDetectionManager( _ fallDetectionManager: CMFallDetectionManager, didDetect event: CMFallDetectionEvent, completionHandler handler: @escaping () -> Void )
- 添加了对应的Info.plist键和权限
解决方案
以下是导致该崩溃的常见原因及修复方法:
- 代理对象被提前释放:
CMFallDetectionManager对delegate持有弱引用,如果你的代理实例是局部变量(比如在某个方法内创建),会被系统快速释放,导致检测时找不到有效代理。需将代理和CMFallDetectionManager实例作为类属性持有,确保生命周期覆盖检测全程:
import CoreMotion class FallDetectionHandler: NSObject, CMFallDetectionDelegate { // 作为类属性持有,避免被释放 private let fallDetectionManager = CMFallDetectionManager() override init() { super.init() fallDetectionManager.delegate = self setupDetection() } private func setupDetection() { guard CMFallDetectionManager.isAvailable() else { return } CMFallDetectionManager.requestAuthorization { [weak self] status in guard status == .authorized else { return } self?.fallDetectionManager.startDetection() } } func fallDetectionManager( _ fallDetectionManager: CMFallDetectionManager, didDetect event: CMFallDetectionEvent, completionHandler handler: @escaping () -> Void ) { // 处理跌倒事件逻辑 handler() } }
- 代理类未继承NSObject:
CMFallDetectionDelegate是基于Objective-C的协议,代理类必须继承NSObject才能被系统正确识别。检查你的代理类声明,确保包含NSObject父类:
// 正确写法 class YourDelegateClass: NSObject, CMFallDetectionDelegate { ... } // 错误写法(会导致代理无效) class YourDelegateClass: CMFallDetectionDelegate { ... }
方法签名不匹配:
仔细核对代理方法的签名,确保参数类型、名称、修饰符完全一致,包括@escaping关键字、参数标签等。任何细微的拼写错误或类型不匹配都会导致系统认为代理未实现必要方法,触发崩溃。未完成授权就启动检测:
必须在用户授权成功后再调用startDetection(),否则会导致CMFallDetectionManager内部状态异常,间接引发代理有效性校验失败。确保授权流程完成后再启动检测。
内容的提问来源于stack exchange,提问作者coding_enthusiast
相关产品推荐
相关产品推荐

