1

下面的代码几乎是 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
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但它并没有说接收者保留了队列,所以这可能不是你可以安全假设的。我的建议是不要自动释放队列。相反,viewDidUnload在调用stopAccelerometerUpdatesmotionManager 后将其释放。

于 2011-06-01T21:37:34.950 回答