我有一个加速计,我用它来稍微移动UIImageviews的层数,以获得一些深度感知。
下面是我用来实例化viewdidload方法中的动画和加速度计的代码。
UIAccelerometer *accelerator = [UIAccelerometer sharedAccelerometer];
accelerator.delegate = self;
accelerator.updateInterval = 0.1f;
animateLayer0 = [CABasicAnimation animationWithKeyPath:@"position"];
animateLayer1 = [CABasicAnimation animationWithKeyPath:@"position"];
animateLayer2 = [CABasicAnimation animationWithKeyPath:@"position"];
animateLayer0.duration = 0.1;
animateLayer0.fillMode = kCAFillModeForwards;
animateLayer0.removedOnCompletion = false;
animateLayer1.duration = 0.1;
animateLayer1.fillMode = kCAFillModeForwards;
animateLayer1.removedOnCompletion = false;
animateLayer2.duration = 0.1;
animateLayer2.fillMode = kCAFillModeForwards;
animateLayer2.removedOnCompletion = false;下面是加速度计函数的代码:
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration{
self.difference = 0 - acceleration.y;
if (fabsf(self.difference) > 0.01) {
for (int i = 0; i < self.accLayerPoints0.count; i++) {
NSValue *val = [self.accLayerPoints0 objectAtIndex:i];
CGPoint origin = [val CGPointValue];
float x = origin.x + (acceleration.y * ACC_LAYER0_THRESHOLD);
[animateLayer0 setToValue:[NSValue valueWithCGPoint:CGPointMake(x, origin.y)]];
UIImageView *layer0 = [self.accLayerObjects0 objectAtIndex:i];
[layer0.layer addAnimation:animateLayer0 forKey:nil];
}
for (int i = 0; i < self.accLayerPoints1.count; i++) {
NSValue *val = [self.accLayerPoints1 objectAtIndex:i];
CGPoint origin = [val CGPointValue];
float x = origin.x + (acceleration.y * ACC_LAYER1_THRESHOLD);
[animateLayer1 setToValue:[NSValue valueWithCGPoint:CGPointMake(x, origin.y)]];
UIImageView *layer0 = [self.accLayerObjects1 objectAtIndex:i];
[layer0.layer addAnimation:animateLayer1 forKey:nil];
}
for (int i = 0; i < self.accLayerPoints2.count; i++) {
NSValue *val = [self.accLayerPoints2 objectAtIndex:i];
CGPoint origin = [val CGPointValue];
float x = origin.x + (acceleration.y * ACC_LAYER2_THRESHOLD);
[animateLayer2 setToValue:[NSValue valueWithCGPoint:CGPointMake(x, origin.y)]];
UIImageView *layer0 = [self.accLayerObjects2 objectAtIndex:i];
[layer0.layer addAnimation:animateLayer2 forKey:nil];
}
}
}我的问题是,过了一段时间后,ipad开始出现性能问题,开始滞后。我使用了分配工具来验证是不是加速计函数中的代码导致了这个问题。
有没有办法释放不再使用的对象或清理代码?我使用的是ARC,所以我不确定清洁是如何进行的。
发布于 2012-07-25 21:01:06
我不认为分配是你的问题。我敢打赌,如果你使用时间分析器,你会看到你阻塞了主线程的所有加速度计活动。对于每个单独的加速度计事件,你都是在许多非常紧密的循环中做这一切,这可能比你意识到的要多得多。
考虑将位置计算放在后台队列中,并更新主线程上UI对象的位置(这部分是必需的,因为从后台队列更新UI通常是不安全的)。这可以通过将实际的UI更新命令分派到主队列来实现。也许用你的背景计算值创建一个在主队列上调用的漏斗点(-updateUIWithDictionaryContainingComputedPositionsForEachLayer:,)。
同样值得怀疑的是,你需要每一个加速度计事件。限制处理(中央调度中心也可以提供帮助,或者一个简单的倒计时-重新启动-如果新事件NSTimer),这样就不会处理每个单独的事件。你需要进行实验,在流畅的动画效果和高效的响应性之间找到感知上的“甜蜜点”,但我敢打赌,获得流畅的视觉效果所需的更新次数比你正在处理的加速计事件的数量要少得多。
https://stackoverflow.com/questions/11649413
复制相似问题