7

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

@property (strong, nonatomic) CMMotionManager *MManager;

在它的吸气剂中,我做惰性实例化。当控制器的视图加载时,我调用这个方法

- (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然后应用程序立即崩溃,我得到了这个线程日志

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错地方了吗?

4

1 回答 1

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);
}];

事实证明,这不是使用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).

于 2013-11-19T23:28:21.893 回答