在检测到加速度计“轻弹”时,我无法触发 performSelector afterDelay 命令。检测到移动(记录“到达此处”),但由于某种原因,传递给 performSelector 命令的选择器未触发。
我设置了一个测试 block ,并从中成功运行了一个 performSelector,所以我认为问题不是 block 本身造成的,也许这与运行 CoreMotion 的线程有关? (我必须承认对 block /线程/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
}
最佳答案
我最终到达了那里(首先考虑切换到使用访问加速度计的 UIAccelerator 方法的想法 - 但后来发现这将在未来的 iOS 版本中被弃用(参见“运动事件类型”部分here )
基本上,当检测到运动时执行的 block 中的代码可能不会在主线程上运行,这可能会导致问题,尤其是与 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 .希望这可能对在同一领域苦苦挣扎的人们有所帮助,如果您需要更多信息/代码,请随时发表评论。
关于objective-c - 无法运行 performSelector : afterDelay from CoreMotion Block,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8855310/