在我的根 Controller 中,我有一个属性 CMMotionManager
@property (strong, nonatomic) CMMotionManager *MManager;
在它的 getter 中,我进行了惰性实例化。当 Controller 的 View 加载时,我调用这个方法
- (void)reloadAccelerometer {
NSLog(@"Away we go");
self.MManager.deviceMotionUpdateInterval = 10.0/60.0;
[self.MManager startDeviceMotionUpdatesToQueue:self.queue withHandler:^(CMDeviceMotion *motion, NSError *error) {
NSLog(@"Y values is: %f", motion.userAcceleration.y);
}];
}
我在 NSLog
中看到“Away we go”,然后应用程序立即崩溃,我得到了这个线程日志
libsystem_platform.dylib`spin_lock$VARIANT$mp:
0x39a87814: movs r1, #1
libsystem_platform.dylib`OSSpinLockLock$VARIANT$mp + 2:
0x39a87816: ldrex r2, [r0]
0x39a8781a: cmp r2, #0
0x39a8781c: it ne
0x39a8781e: bne.w 0x39a893ec ; _OSSpinLockLockSlow$shim
0x39a87822: strex r2, r1, [r0]
0x39a87826: cmp r2, #0
0x39a87828: bne 0x39a87816 ; OSSpinLockLock$VARIANT$mp + 2
0x39a8782a: dmb ish
0x39a8782e: bx lr
我的错误是什么?我是否将 reloadAccelerometer
放在了错误的位置?
最佳答案
我试图在我的 iOS 应用程序中做一些类似的事情,并花了 永远 试图找出崩溃的原因。这是一个非常神秘(而且讨厌)的异常。在阅读崩溃报告后,我最终弄明白了 OSSpinLock
与线程/队列管理问题有关。
NSOperationQueue
是这里的罪魁祸首。您的代码没有显示您是如何创建 NSOperationQueue
的,但我认为它是这样的:
NSOperationQueue *aQueue = [[NSOperationQueue alloc] init]; // Do NOT do this
[self.MManager startDeviceMotionUpdatesToQueue:aQueue withHandler:^(CMDeviceMotion *motion, NSError *error) {
NSLog(@"Y values is: %f", motion.userAcceleration.y);
}];
事实证明,这不是 NSOperationQueue
的使用方式。 aQueue
对象是崩溃的原因。
要正确设置操作队列并避免崩溃,您应该将 CMMotionManager 移动到不同的线程。然后告诉 NSOperationQueue 使用 currentQueue
,而不是 mainQueue
。 Apple 建议它不要在 mainQueue
上运行,但是如果您的应用程序当前在主队列中运行,那么我看不出 currentQueue
有何不同。我尝试使用 GCD 将下面的代码移动到不同的队列,但从未调用任何代码。
您的最终代码应如下所示:
// Check if Motion / Location services are available
if (motionManager.deviceMotionAvailable == YES && motionManager.accelerometerAvailable == YES) {
NSLog(@"Away we go");
self.MManager.deviceMotionUpdateInterval = 10.0/60.0;
[self.MManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMDeviceMotion *motion, NSError *error) {
NSLog(@"Y values is: %f", motion.userAcceleration.y);
}];
} else {
// Motion / Accelerometer services unavailable
}
我还应该注意,您创建的 CMMotionManager
属性(据我所知)对于 (strong, nonatomic)
是正确的。
关于ios - 我在 Controller 内调用 startDeviceMotionUpdatesToQueue 时得到 OSSpinLockLock,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19570388/