以下のコードは、Beginning Iphone4DevelopmentのShakeandBakeの例のレプリカに近いものです。CMAcceleration Acceleration = accelerometerData.acceleration;の前に、BOOLifステートメントがありません。何回でも振って結果を更新してほしいからです。同じコードを完璧に実行するボタンがあります。コードを実行してiPhoneを振ると、クラッシュします。この機能を実現するために何が欠けていますか?shakeメソッドと同じコードをボタンで実行することはできませんか?
Example.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
Example.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