无法从CoreMotion Block运行performSelector:afterDelay

时间:2012-01-13 18:21:25

标签: objective-c ios objective-c-blocks core-motion

我在检测到加速度计' flick'时,无法触发performSelector afterDelay命令。检测到移动('此处已记录),但由于某种原因,传递给performSelector命令的选择器未触发。

我设置了一个测试块,并成功运行了一个performSelector,所以我不认为块本身会导致问题,也许它与CoreMotion运行的线程有关。 ? (我必须承认在块/线程/ CoreMotion上有点模糊)

任何线索都会非常感激。感谢。

- (void)viewDidLoad
{
    [super viewDidLoad];
    //Do any additional setup after loading the view, typically from a nib.

    motionManager = [[CMMotionManager alloc] init];
    if(motionManager.accelerometerAvailable)
    {
        motionManager.accelerometerUpdateInterval = 0.1;
        NSOperationQueue *motionQueue = [[NSOperationQueue alloc] init]; 
        [motionManager startAccelerometerUpdatesToQueue: motionQueue withHandler: ^(CMAccelerometerData *data, NSError *error) 
         {
             float accelerationThreshold = 1.2;

             CMAcceleration userAcceleration = data.acceleration;
             if (fabs(userAcceleration.x) > accelerationThreshold)               
             {
                 NSLog(@"Got here"); //runs
                 [self performSelector:@selector(test) withObject:nil afterDelay:1.0];
             }
         }];
    }
}

-(void) test
{
    NSLog(@"perform selector after delay worked"); //doesn't run
}

1 个答案:

答案 0 :(得分:1)

我最终到达那里(在第一次尝试使用UIAccelerator方法访问加速度计的想法之后 - 然后发现在未来的iOS版本中不推荐使用它(请参阅“运动事件类型”一节) here

基本上,在检测到运动时执行的块中的代码可能无法在主线程上运行,这可能会导致问题,尤其是与UIView相关的代码。

确保在主线程上执行代码的方法是调用:

[self performSelectorOnMainThread:@selector(test) withObject:nil waitUntilDone:false]; 

而不是正常:

[self performSelector:@selector(test) withObject:nil afterDelay:1.0]; 

哦,我发现谷歌书中的解决方案摘自优秀的Beginning IPhone 4 Development: Exploring the IOS SDK。希望这可能会对在同一区域挣扎的人有所帮助,如果您想要更多信息/代码,请随时发表评论。