1

以下のコードは、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
4

2 に答える 2

1

メインスレッド以外のスレッドでアラートビューを作成して表示しようとしています。UIの更新は、メインスレッドでのみ実行されます。を使用performSelectorOnMainThread:withObject:waitUntilDone:して、メインスレッドを作成して表示する必要があります。

このように、いつでもUIの更新リクエストを追加できます– </ p>

dispatch_async(dispatch_get_main_queue(),^{
    // Put all your UI updates here; 
});
于 2011-06-01T17:55:36.017 に答える
0

私には魚のように見える部分はですNSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];

motionManagerがキューにディスパッチしている間、キューにぶら下がっているところはどこにもありません。ドキュメントを確認しましstartAccelerometerUpdatesToQueueたが、受信者がキューを保持しているとは言われていないので、おそらく安全に想定できるものではありません。私の提案は、キューを自動解放しないことです。代わりに、motionManagerviewDidUnloadを呼び出した後にリリースしてください。stopAccelerometerUpdates

于 2011-06-01T21:37:34.950 に答える