在控制器内调用startDeviceMotionUpdatesToQueue时,我得到了OSSpinLockLock

Mor*_*lde 7 objective-c ios core-motion

在我的根控制器中,我有一个属性 CMMotionManager

@property (strong, nonatomic) CMMotionManager *MManager;
Run Code Online (Sandbox Code Playgroud)

在它的吸气器中我做懒惰的实例化.当控制器的视图加载时,我调用此方法

- (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);
    }];
}
Run Code Online (Sandbox Code Playgroud)

我看到"离开我们去" NSLog然后立即应用程序崩溃,我得到这个线程日志

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
Run Code Online (Sandbox Code Playgroud)

我的错是什么?我把它reloadAccelerometer放在了错误的地方吗?

Sam*_*cer 7

我试图做我的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);
}];
Run Code Online (Sandbox Code Playgroud)

事实证明,这不是使用的方式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
}
Run Code Online (Sandbox Code Playgroud)

我还应该注意到你的CMMotionManager财产创造(据我所知)是正确的(strong, nonatomic).