下面的代码几乎是 Iphone 4 Development 中 Shake and Bake 示例的复制品。在 CMAcceleration 加速 = accelerometerData.acceleration 之前缺少 BOOL if 语句;因为我希望这个人可以根据需要多次摇动和刷新结果。我有一个可以完美执行相同代码的按钮。当我运行代码并摇动 iphone 时,它崩溃了。我错过了什么可以使这项工作?您不能使用按钮运行与使用摇动方法相同的代码吗?
例子.h
#import <CoreMotion/CoreMotion.h>
#define kAccelerationThreshold 1.7
#define kUpdateInterval (1.0f/10.0f)
@interface exampleViewController : UIViewController {
CMMotionManager *motionManager;
}
@property (retain,nonatomic) CMMotionManager *motionManager;
@end
例子.m
@synthesize motionManager;
-(void)viewDidLoad {
self.motionManager = [[[CMMotionManager alloc] init] autorelease];
motionManager.accelerometerUpdateInterval = kUpdateInterval;
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
[motionManager startAccelerometerUpdatesToQueue:queue
withHandler:
^(CMAccelerometerData *accelerometerData, NSError *error){
if (error) {
[motionManager stopAccelerometerUpdates];
} else {
CMAcceleration acceleration = accelerometerData.acceleration;
if (acceleration.x > kAccelerationThreshold
|| acceleration.y > kAccelerationThreshold
|| acceleration.z > kAccelerationThreshold){
// There is a bunch of other stuff here, but it all works using a button called shake....
example4.hidden = NO;
select1.text = first;
display.text = [[NSString alloc] initWithFormat: @"%@", first];
}
}
}];
}
- (void)dealloc
{
[super dealloc];
[motionManager release];
}
- (void)viewDidUnload {
[super viewDidUnload];
self.motionManager = nil;
}
@end