我第一次玩Core Motion并遇到了一个问题,我无法弄清楚发生了什么。我相信这将是一个简单的问题。这是一些代码:
.h文件
#import <UIKit/UIKit.h>
#import <CoreMotion/CoreMotion.h>
@interface TempVC : UIViewController {
CMMotionManager *motionManager;
CMAttitude *referenceAttitude;
CMAttitude *attitude;
}
- (void)updateData;
@end
.m文件
#import "TempVC.h"
#define DEGREES(radians) (radians / M_PI * 180.0)
@implementation TempVC
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor brownColor];
motionManager = [[CMMotionManager alloc] init];
referenceAttitude = nil;
CMDeviceMotion *dm = motionManager.deviceMotion;
attitude = dm.attitude;
referenceAttitude = [attitude retain];
motionManager.deviceMotionUpdateInterval = 0.1;
[motionManager startDeviceMotionUpdates];
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(updateData) userInfo:nil repeats:YES];
}
- (void)updateData
{
attitude = motionManager.deviceMotion.attitude;
[attitude multiplyByInverseOfAttitude:referenceAttitude];
NSLog(@"\n Roll: %.0f\n Pitch: %.0f\n Yaw: %.0f",DEGREES(attitude.roll), DEGREES(attitude.pitch), DEGREES(attitude.yaw));
}
此代码将崩溃,但没有真正指示出现了什么问题。如果我发表评论
[attitude multiplyByInverseOfAttitude:referenceAttitude];
一切正常???我是否实施了错误的引用?
答案 0 :(得分:2)
在开始更新之前,您可以访问CMMotionManager的deviceMotion属性。在那里你存储你的referenceAttitude,当时仍然是零。调用updateData后几毫秒[attitude multiplyByInverseOfAttitude:referenceAttitude];
将失败。
尝试在第一次调用updateData时设置referenceAttitude,它应该可以工作。